Wednesday, March 14, 2012

Overwriting WndProc()

The operating system Windows works event oriented, meaning programs do not ask continously for the state of certain system variables or something else, but they are informed themselves by events (messages) about changes.

In this post I want to show, how to overwrite the function, which receives the messages send from the operating system to the C# application, and thus is able to manipulate the data processing.

The function responsible for this is called WndProc() and is part of every form class. While the application is running, Windows sends continously meesages to the application, WndProc() receives them. Windows notifies our program about practically everything  which could be interesting for it, starting from the movement of the mouse cursor over the activation of another application to the click on the exit button on the form. In general all actions, which the user undertakes on the form, are registered by Windows, processes and then send back to the application for processing. The case, that the user clicks "X" for quitting our C# aplication, provokes the following action chain: Windows recognizes a mouse click in the area of our application, sends the event to the application, which then determines then via the position that "X" was clicked and exits itself.

That much to the theory, now to the practical realization: As already mentioned WndProc() is already a function of the Form class, so we have to overwrite it, which can be done with the key word override.
If we enter in the .Net development studio the first characters of the signature protected override void WndProc(ref Message m), C# automatically completes this to

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
}

The added line expresses, that after the call of your function, the original function is called.
If you delete this line, the application cannot even start, since all incoming events "end" in our function and are not processed further.

To get an intuition of which and how many events are received, you could for example add a ListBox to the form and add the following line to the function:
listBox1.Items.Add(m.ToString());

Obviously, this post was kept pretty abstract, but I hope to show you soon some interesting applications, which can be realized based upon the knowledge from this post.

(Edit: In the next post I show, how to use this function to determine whether hardware settings have changed. With this for example can be checked, whether a USB flash drive was pluggin in or a CD inserted.)

No comments:

Post a Comment