How to override the message loop in winforms?
I have a situation where I need to do some custom message filtering.
Unfortunately I need more functionality than provided by the
IMessageFilter system or by overriding a Form's wndproc() method.
What I need is to be able to run code before and after a message is
processed and optionally drop selected messages.
As I understand it:
The IMessageFilter system only allows filtering out selected messages
(can't run code after they have been processed)
A Form's wndproc method only sees messages destined for that form. (I
need to handle all messages for the entire application)
In an unmanaged application say in visual c++ it would be a simple
matter of implementing ones own getmessage/dispatchmessage loop. In
the dotnet framework the actual message loop is implemented in native
code and is inaccessible to the programmer.
Does anyone know a solution for this?
Unfortunately, the only thing you can do outside the form is use Application.AddMessageFilter to add your own filter, and (as you've surmised), this only works on capturing a message before it is dispatched to the window. What you could possibly do (and this would be one heck of a hack), is use a combination of AddMessageFilter and a Mediator to control what happens. What you'd do is hook into the WndProc of each form, and pass the details to the mediator to work out whether or not the message could be processed.
Ther's actually a fair bit out in the wilds of the Internet about this. I have done similar but not with .netty Winformy things.
Search on Jeff Richter or forms message intercept and you might get there more quickly.
Sorry all I have here is C
Best of Luck
This articles code may give you what you are looking for
While the explanation of the code in the article leaves something to be desired, it does cover hooking into events including global events that aren't destined for your window, specifically mouse and keyboard hooks. This may or not work for your needs.