Back in my Delphi days there was a useful set of functions in the RTL that allowed you to create a hidden window with which to deal with Windows messages without the need for a windowed component, such as one derived from TWinControl. These functions were AllocateHWnd and DeallocateHWnd.
However, moving on to .NET and Winforms I couldn’t find a simple or straightforward way to do this using the existing framework controls so set about last evening creating my own implementation, the result was a new static class called MessageWindow.
MessageWindow uses a lot of P/Invoke calls unfortunately and is thoroughly non-portable but then, if you have to intercept Windows messages you’re most likely going to be on Windows.
Disregarding non-public members the MessageWindow class exposed looks something like this:
public static class MessageWindow
{
public static MessageWindowInstance Create(MessageWindowProc windowProc);
public static void Destroy(MessageWindowInstance windowInstance);
}
There are two simple calls, Create and Destroy which allow you to create a window for messaging and then once you’re done, destroy it. In-fact, I go one step further here, because Create returns a MessageWindowInstance, which represents our window you can actually just call MessageWindowInstance.Dispose() and that will release the window as well.
The MessageWindowInstance class looks something like this:
public class MessageWindowInstance : IDisposable
{
public void Dispose();
public IntPtr Handle
{
get;
}
}
Like AllocateHWND which expected a TWndMethod, our method requires you pass in a delegate, MessageWindowProc which follows the same pattern as the framework’s message handlers:
public delegate void MessageWindowProc(ref Message msg);
So putting it all together you first create your window proc:
private static void WindowProc(ref Message msg)
{
// Handle message here
}
Next, you create your window:
MessageWindowInstance window = MessageWindow.Create(new MessageWindowProc(WindowProc));
And finally, once you’re done, you release your window:
// First way
MessageWindow.Destroy(window);
// Second way
window.Dispose();
Hopefully this will work as well as the Delphi versions, I’m currently using it in a clipboard chain. The code is available on my Github or you can download the source and binaries directly from here.