问题描述
肯定有一种方便的方法:
There is certainly a convenient way to do this :
我已经在主窗体上实现了关于鼠标拖动行为的移动窗口。 >并且我希望MouseClick / Move事件被表单拦截,而不是被其中的控件拦截。
I have implemented a "Move Window" on mouse drag behavior on my main form,
and I would like the MouseClick/Move event to be intercepted by the form, not by controls that are in it.
我想找到一个等效项/副本鼠标事件的 KeyPreview属性
I would like to find an Equivalent to/replicate the "KeyPreview" property for Mouse Events
此外,我还要避免在12个控件的鼠标事件中分别将鼠标事件重定向到Main Form方法12次(这是到目前为止,我已经找到了丑陋的解决方法)
Besides I want to avoid Redirecting the Mouse Event to the Main Form Method 12 times in 12 Controls' Mouse events individually (which is the ugly workaround I have Found so far)
有什么想法吗?
推荐答案
订阅所有控件MouseMove事件(考虑对嵌套控件进行递归操作)
Subscribe to all controls MouseMove events (consider do it recursively for nested controls)
foreach (Control control in Controls)
control.MouseMove += RedirectMouseMove;
并在此事件处理程序中举起MouseMove
And raise MouseMove inside this event handler
private void RedirectMouseMove(object sender, MouseEventArgs e)
{
Control control = (Control)sender;
Point screenPoint = control.PointToScreen(new Point(e.X, e.Y));
Point formPoint = PointToClient(screenPoint);
MouseEventArgs args = new MouseEventArgs(e.Button, e.Clicks,
formPoint.X, formPoint.Y, e.Delta);
OnMouseMove(args);
}
请记住,控件会接收具有本地控件坐标的MouseEvent。因此,您需要将其转换为表单坐标。
嵌套控件可能有缺点,但我留给您使用(例如,调用Parent.PointToClient)
Keep in mind that controls receive MouseEvents with local coordinates of control. So you need to convert it to form coordinates.There are could be drawbacks with nested controls, but I leave it to you (e.g. call Parent.PointToClient)
UPDATE :您仍然可以处理控制事件-只需再订阅一次事件即可。
UPDATE: You are still will be able to handle events of control - just subscribe to event one more time.
这篇关于Winforms:首先在主窗体上拦截鼠标事件,而不是在控件上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!