Click to See Complete Forum and Search --> : (Beginner) Magic of WndProc


haven1433
June 17th, 2009, 02:47 PM
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

...

WNDCLASSEX wndclassex;
wndclassex.lpfnWndProc = WndProc;

This final line tells windows what function name will respond to events. But how does it work? It seems that a pointer is being directed to a function, and that windows then calls that function from its own main somewhere else. Is it possible to copy this effect?

I'm wanting to define a single WndProc that handles messages by splitting the messages into other functions, defined by the programmer. The programmer could select certain messages to answer like:

setResponseToWM_COMMAND( menuListener );
setResponseToWM_LBUTTONDOWN( leftButtonDown );

or perhaps

function.command = menuListener;
function.lbuttondown = leftButtonDown;

where menuListener() and leftButtonDown() are functions that specifically handle events for the menu or events for left clicking. Leaving a pointer set to NULL would create default behavior, and setting a pointer to a function would have that function called. Is there a way to do this, or am I stuck with C's syntax of doling out from the one function only? This method would make the code easier to reuse, separating out large sections of complicated casting and Windows types.

Thanks for any help,

haven1433

JVene
June 17th, 2009, 06:14 PM
Yes, in a manner of speaking that's what frameworks like MFC, WTL and QT do.

For win32 development, which is what you're indicating, the typical construction is to create a large switch that's rather ugly.

MFC uses message maps, not unlike the macro style list of function pointers you indicated in your post. This creates a table which MFC's version of the WndProc uses to dispatch a message to a function, with message parameters 'cracked' or 'parsed' from LPARAM and WPARAM into more meaningful values, like integers x and y for coordinates relative to mouse messages.

Many of these frameworks are portable across operating systems. QT and wxWidgets, for example, allow one application body (with very few exceptions) to compile and run on Mac, Linux and Windows, including a number of handheld devices.

MFC is Windows only, but it offers fairly 'complete' GUI support for current operating system features.