Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - Winforms : Intercepting Mouse Event on Main Form first, not on Controls

There is certainly a convenient way to do this :

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.

I would like to find an Equivalent to/replicate the "KeyPreview" property for Mouse Events

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)

Any Ideas ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Subscribe to all controls MouseMove events (consider do it recursively for nested controls)

foreach (Control control in Controls)
    control.MouseMove += RedirectMouseMove;

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);
}

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: You are still will be able to handle events of control - just subscribe to event one more time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...