Winform 控件鼠标离开事件 中 鼠标进入子控件也会触发mouseleave事件处理
最近在做一个关于语音与文本互相转化的小工具,利用的是百度的语音与文本转化接口。由于百度的语音转文本极速版接口中,只支持pcm格式以及处理60s以内的文件,故而工具中使用到了其中使用到了将包括 mp3,m4a。。。等格式音频文件转化成pcm格式。
本工具客户有一个要求,如下图所示
用户在鼠标滑动到 开通VIP(panel1)按钮的时候 需要将 用户中心(panel2)的相关信息展示出来 ,并且里面的继续购买和退出登录等按钮要容许点击,当鼠标离开panel1不进入会员中心panel2或者是鼠标离开 会员中心panel2的时候,该会员中心panel2需要及时隐藏,很常规的很正常的一个要求。
按照描述,给panel1和panel2分别添加mouseenter 和mouseleave事件组合。但编者在实际使用过程中发现,在鼠标由 panel1滑动到panel2的过程中,始终无法触碰到该panel2中的子控件 (退出登录。。。。),如果鼠标一直在panel2的空白部分则不会出现pane2消失的问题。
在网上也查询了一些资料!
第一步:新建一个类SelfDefinePanel.cs 重写panel的OnControlAdded 和 OnMouseLeave 事件
具体代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TransferSolution
{
public class SelfDefinePanel : Panel
{
public SelfDefinePanel()
{
SetStyle(ControlStyles.DoubleBuffer, true);//ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.UserPaint, true);
this.UpdateStyles();
}
/// <summary>
/// 重写OnControlAdded方法,为每个子控件添加MouseLeave事件
/// </summary>
/// <param name="e"></param>
protected override void OnControlAdded(ControlEventArgs e)
{
Control control = e.Control; // 获取添加的子控件
control.MouseLeave += this.SubControlLeave; // 当鼠标离开该子控件时判断是否是离开SelfDefinePanel
base.OnControlAdded(e);
}
/// <summary>
/// 重写OnMouseLeave事件,如果是离开本身的矩形区域则发生 base.OnMouseLeave(e);
/// </summary>
/// <param name="e"></param>
protected override void OnMouseLeave(EventArgs e)
{
//Console.WriteLine(" OnMouseLeave ClientRectangle ------------------ " + this.RectangleToScreen(this.ClientRectangle));
//判断鼠标是否还在本控件的矩形区域内
if (!this.RectangleToScreen(this.ClientRectangle).Contains(Control.MousePosition)) // this.RectangleToScreen(this.ClientRectangle) 映射为屏幕的矩形
{
base.OnMouseLeave(e);
this.Visible = false;
//Console.WriteLine(" ------------------ SelfDefinePanel OnMouseLeave ------------------ ");
}
}
/// <summary>
/// 子控件鼠标离开时也要做相应的判断
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SubControlLeave(Object sender, EventArgs e)
{
//Console.WriteLine(" SubControlLeave ClientRectangle ------------------ " + this.RectangleToScreen(this.ClientRectangle));
//判断鼠标是否还在本控件的矩形区域内
if (!this.RectangleToScreen(this.ClientRectangle).Contains(Control.MousePosition))
{
base.OnMouseLeave(e);
this.Visible = false;
//Console.WriteLine(" ------------------ SubControlLeave ------------------ ");
}
}
}
}
第二步:在form中的designer文件中 修改对应的panel 具体如下 其中的penvip 就是 下面的会员中心的panel2名
第三步:给 上面的panel1(btnVIP)按钮绑定mouseenter和mouseleave两个事件 并在mouseleave事件中修改部分代码如下
原则上操作到这个步骤的话 效果基本已经实现了,但是还有一个优化的地方,就是鼠标在滑动到会员中心过程中,如果速度不快
还是会出现会员中心panel2消失的问题,效果切换不是很平滑。
经过分析,原因是在开通vip的panel1和会员中心得panel2中间有一个空白地带,采用的方式即第四步
第四步:在开通vip和会员中心panel中 新增一个panel 使其上半部分盖住panel1,下半部分盖住会员中心的panel2.
到此完成效果!