我有一个表格,上面有很多控件.如何检测鼠标何时离开表格?我已尝试为每个控件和表单连接一个MouseLeave事件,但这不起作用,因为当鼠标经过控件时,这些事件会一直触发.有没有一种实际有效的方法.
你应该听:
MouseLeave窗体的所有控件的事件
表单的MouseLeave事件
只需将您的侦听器链接到一个函数,该函数检查光标是否在表单客户端中.
试试这个:
protected override void OnControlAdded(ControlEventArgs e) { SubscribeEvents(e.Control); base.OnControlAdded(e); } protected override void OnControlRemoved(ControlEventArgs e) { UnsubscribeEvents(e.Control); base.OnControlRemoved(e); } private void SubscribeEvents(Control control) { control.MouseLeave += new EventHandler(control_MouseLeave); control.ControlAdded += new ControlEventHandler(control_ControlAdded); control.ControlRemoved += new ControlEventHandler(control_ControlRemoved); foreach (Control innerControl in control.Controls) { SubscribeEvents(innerControl); } } private void UnsubscribeEvents(Control control) { control.MouseLeave -= new EventHandler(control_MouseLeave); control.ControlAdded -= new ControlEventHandler(control_ControlAdded); control.ControlRemoved -= new ControlEventHandler(control_ControlRemoved); foreach (Control innerControl in control.Controls) { UnsubscribeEvents(innerControl); } } private void control_ControlAdded(object sender, ControlEventArgs e) { SubscribeEvents(e.Control); } private void control_ControlRemoved(object sender, ControlEventArgs e) { UnsubscribeEvents(e.Control); } protected override void OnMouseLeave(EventArgs e) { CheckMouseLeave(); base.OnMouseLeave(e); } private void control_MouseLeave(object sender, EventArgs e) { CheckMouseLeave(); } private void CheckMouseLeave() { Point pt = PointToClient(Cursor.Position); if (ClientRectangle.Contains(pt) == false) { OnMouseLeftFrom(); } } private void OnMouseLeftFrom() { Console.WriteLine("Mouse left the form"); }