Thursday, February 24, 2005

Hernán Di Pietro's Message Cracker Wizard

Recently came across Hernán Di Pietro's Message Cracker Wizard. No more digging through windowsx.h to look for function signatures. You can also find it on code project. And here's his blog http://hernandp.blogspot.com/

For those who aren't familiar with message crackers here's a very very brief intro (for a better and more detailed article click here):

In most Win32 programs, the WndProc consists mainly of one huuuge switch-case. Each of the case statements looks something like:

case WM_SIZE:
int width = LOWORD(lParam), height = HIWORD(lParam);
RedoLayout(width, height);
// et cetera ...
return 0;


To make sense of the message parameters, you need to do a LOWORD/HIWORD or use a bit mask as per the API docs. A message cracker is a pre-processor macro which converts the LPARAM and WPARAM to more sensible values and passes these values to a function which you provide. Each WM_ message has a corresponding HANDLE_WM_ macro defined in windowsx.h. Along with the macro you see a comment giving you the signature of the function you are expected to provide.

For example here is the entry for WM_SIZE as given in windowsx.h:

/* void Cls_OnSize(HWND hwnd, UINT state, int cx, int cy) */
#define HANDLE_WM_SIZE(hwnd, wParam, lParam, fn) ((fn)((hwnd), (UINT)(wParam), (int)(short)LOWORD(lParam), (int)(short)HIWORD(lParam)), 0L)


So to use the message cracker you change your case to:
case WM_SIZE:
return HANDLE_WM_SIZE(hwnd, wParam, lParam, myWindow_OnSize);


You then place all your message handling in myWindow_OnSize as in:
void mainWindow_OnSize(HWND hwnd, UINT state, int cx, int cy){
RedoLayout(cx, cy);
}


You can further reduce your coding effort using the HANDLE_MSG macro. For this, you replace the entire case block with:
HANDLE_MSG(hwnd, WM_SIZE, mainWindiow_OnSize)
Note: For this to work, the parameters to your WndProc must be named wParam and lParam.

The advantages? 1) You don't need to remember whether your parameter was in the LOWORD or HIWORD or in the least significant byte. 2) The code is more modular. Each event is handled in a separate function. 3) Code is neat.

No comments:

About Me

My photo
C/C++ Programmer doing CAD on Windows. Some web development experience. Bangalorean.

Blog Archive

Labels