Use WndProc to read Windows messages in C#


This example shows how you can determine what windows messages a program is receiving. (In earlier versions of Visual Basic, you could intercept messages by using API functions to install a WndProc handler. That was called “subclassing” so the method described here is also sometimes called “subclassing,” even though neither technique is truly subclassing in the object-oriented sense.)

Every form has a method called WndProc that processes Windows messages. This function handles messages telling the form to move, resize, redraw, close, display system menus, and all sorts of other things. Without it, the form can’t do anything.

To see what messages the form is receiving, you can override WndProc as shown in the following code.

// Override WndProc to watch for messages.
protected override void WndProc(ref Message m)
    base.WndProc(ref m);

This function receives a Message object as a parameter and uses its ToString method to display the message’s name. You could make the program take other actions such as ignoring some messages.

The code then calls the base class’s WndProc method to process the message normally. This is very important! If you don’t process the message normally, the form will not be able to resize itself, draw its interior, and perform other important Windows functions.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in forms, system and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.