整个窗口上的MouseHover / MouseLeave事件

我有Form子类,带有MouseHoverMouseLeave处理程序。 当指针位于窗口的背景上时,事件工作正常,但当指针移动到窗口的控件上时,它会导致MouseLeave事件。

无论如何有一个覆盖整个窗口的事件。

(.NET 2.0,Visual Studio 2005,Windows XP。)

当触发鼠标离开事件时,一个选项是检查指针的当前位置并查看它是否在表单区域内。 我不确定是否有更好的选择。

编辑:我们有一个类似的问题,您可能会感兴趣。 如何检测鼠标是否在C#中的整个表单和子控件中?

只要鼠标进入子控件,就不会触发MouseLeave事件

  protected override void OnMouseLeave(EventArgs e) { if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition))) return; else { base.OnMouseLeave(e); } } 

没有什么好方法可以使MouseLeave可靠地用于容器控件。 用计时器解决这个问题:

 public partial class Form1 : Form { public Form1() { InitializeComponent(); timer1.Interval = 200; timer1.Tick += new EventHandler(timer1_Tick); timer1.Enabled = true; } private bool mEntered; void timer1_Tick(object sender, EventArgs e) { Point pos = this.PointToClient(Cursor.Position); bool entered = this.ClientRectangle.Contains(pos); if (entered != mEntered) { mEntered = entered; if (!entered) { // Do your leave stuff //... } } } } 

在您的用户控件上为您的控件创建一个mousehover事件,像这样(或其他事件类型)

 private void picBoxThumb_MouseHover(object sender, EventArgs e) { // Call Parent OnMouseHover Event OnMouseHover(EventArgs.Empty); } 

在托管UserControl的WinForm上,UserControl可以处理MouseOver,所以将它放在Designer.cs中

 this.thumbImage1.MouseHover += new System.EventHandler(this.ThumbnailMouseHover); 

在WinForm上调用此方法

 private void ThumbnailMouseHover(object sender, EventArgs e) { ThumbImage thumb = (ThumbImage) sender; } 

ThumbImage是usercontrol的类型