判断鼠标是否位于表单上方的最佳方法是什么?
我想出了如何捕获鼠标点击 覆盖整个表单,但此方法对于 MouseEnter
和 MouseLeave
的转换效果不佳。我的表单布局由许多 Panels
和 TableLayoutPanels
组成,因此没有可以监视事件的包罗万象的控件,显然还有一个 MouseLeave
事件按钮并不意味着光标离开了整个表单。有没有人想出一个好方法来解决这个问题?
I figured out how to capture mouse clicks over the entire form, but this method doesn't translate well for MouseEnter
and MouseLeave
. My form layout is made up from many Panels
and TableLayoutPanels
so there's no all-encompassing control I can monitor events for, and obviously a MouseLeave
event for a button doesn't mean the cursor left the entire form. Has anyone figured out a good way to get around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如有人指出此处可以使用 SetWindowsHookEx() 或只是连接MouseMove 事件到窗体中的所有控件上。后者对我来说效果很好。唯一的缺点是,如果您在运行时添加/删除控件,您可能需要另一个解决方案。
As someone pointed out here it's possible to use SetWindowsHookEx() or just hook up MouseMove event onto all controls in the form. The latter works for me fine. The only downside is if you add/remove controls at runtime you might need another solution.
在表单中添加一个计时器,并设置合理的时间间隔(可能是 50 毫秒)。在 Tick 事件处理程序中使用此代码来查看鼠标是否位于表单上:
编辑:这是一个更完整的解决方案,用于检测鼠标位于表单上并且已单击按钮。
timer1Tick()
是表单上计时器的 Tick 事件处理程序。表单上的其他控件不需要额外的事件处理程序。这将使您的表单成为“一个巨大的按钮”:)Add a timer to the form with a reasonable Interval (maybe 50ms). Use this code in the Tick event handler to see if the mouse is over the form:
EDIT: Here is a more complete solution to detecting that the mouse is over the form and that the button has been clicked.
timer1Tick()
is the Tick event handler for a Timer on the form. There is no need to have additional event handlers for the other controls on the form. This will make your form "one giant button" :)在表单和表单控件上执行 MouseEnter 和 MouseLeave 事件;使用布尔值来确定鼠标是进入还是离开。
一个例子是
如果表单上有很多对象,这可能会变得乏味
Do A MouseEnter and MouseLeave event over the Form and Form Controls; use a boolean to determine whether the mouse entered or left.
An example would be
This may get tedious if you have many objects over the form
首先检查 ClientRectangle 是否 包含当前鼠标位置。例如,在您的 MouseMove 处理程序,您可以:
A place to start is to check if the ClientRectangle contains the current mouse position. So, for example, on your MouseMove handler, you could have:
我找到了一些接近我想要的答案,但我最终做了一些不同的事情。我想检测鼠标是否离开表单区域(包括标题栏),这对我有用:
在表单构造函数中,我添加一个计时器:
然后在 tick 方法中,我执行以下操作:
I found a few answers that were close to what I wanted, but I wound up doing something different. I wanted to detect if the mouse left the form area (including the title bar) and this worked for me:
In the form constructor, I add a timer:
Then in the tick method, I do the following: