Hooking the Windows Message Loop in a WinForms Application
Provided by: Dave Juth, Senior Systems Architect
The days of Windows API programming are just a memory for most, but .NET
WinForms applications still allow you to hook Windows messages and respond
to operating system events like the good old days.
The WndProc method of a form provides access to the Windows message loop
for your application. You can monitor these messages in Visual Studio’s
output window with the following code in a form:
override void WndProc(ref Message m)
Trace.WriteLine(m.Msg.ToString() + “: “ + m.ToString());
If you want
respond to a particular message, such as a Windows shutdown event, the
following code example illustrates how to do this:
protected override void WndProc(ref Message m)
== 0×11) // WM_QUERYENDSESSION
// TODO: Do something, then close the form.
There are many events exposed through the
WinForms object model itself, but not all events
are. Knowing how to hook into the operating system’s
messaging is a powerful capability and, thanks to
.NET, easily done.
Return to the tips page