如何检测鼠标何时离开表单? [英] How to detect when the mouse leaves the form?
本文介绍了如何检测鼠标何时离开表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表单,上面有很多控件.如何检测鼠标何时离开表单?我已经尝试为每个控件和表单连接一个 MouseLeave 事件,但这不起作用,因为这些事件在鼠标经过控件时一直触发.有没有实际可行的方法.
I have a form with a lot of controls on it. How can I detect when the mouse leaves the form? I've tried wiring up a MouseLeave event for every single control and the form, but that does not work because those events fire all the time as the mouse passes over controls. Is there a way that actually works.?
推荐答案
你应该听:
- 表单所有控件的MouseLeave事件
- 表单的鼠标离开事件
只需将您的侦听器链接到一个函数,该函数检查光标是否在客户端的表单中.
Just link your listeners to a function that checks whether the cursor is in the forms client are or not.
试试这个:
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");
}
这篇关于如何检测鼠标何时离开表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文