Is this the correct way to handle button messages?
I'm very new to Windows programming. The basic problem is I don't know what I'm doing. :-)
This code works correctly, but the message handling looks kludgy (especially the casting required to make it work). I want to make sure that I'm doing this the correct way, and didn't produce code that works sometimes but not always.
One window, with two buttons on it. Click button 1, a message window pops saying 'button 1 was clicked' ... click button 2, message window pops saying 'button 2 was clicked' ... simple enough.
Code snippets:
Two global variables in callbacks.c:
Code:
HWND g_hwndButton1, g_hwndButton2;
Creating the buttons:
Code:
case WM_CREATE:
{
hInstance = ((LPCREATESTRUCT) lParam)->hInstance;
g_hwndButton1 = CreateWindow(
L"BUTTON", // Predefined class; Unicode assumed
L"OK", // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
10, // x position
10, // y position
100, // Button width
30, // Button height
hWnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
NULL); // Pointer not needed.
g_hwndButton2 = CreateWindow(
L"BUTTON", // Predefined class; Unicode assumed
L"OK", // Button text
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles
10, // x position
80, // y position
100, // Button width
30, // Button height
hWnd, // Parent window
NULL, // No menu.
(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
NULL); // Pointer not needed.
And handling the clicks:
Code:
case WM_COMMAND:
{
switch (LOWORD(wParam))
{
case BN_CLICKED:
{
// which button?
if( lParam == (int)g_hwndButton1 ) {
MessageBox(hWnd, (LPCWSTR)L"Button 1 was clicked / WM_COMMAND", (LPCWSTR)L"Yay", MB_OK | MB_ICONINFORMATION);
return 0;
} else if( lParam == (int)g_hwndButton2 ) {
MessageBox(hWnd, (LPCWSTR)L"Button 2 was clicked / WM_COMMAND", (LPCWSTR)L"Yay", MB_OK | MB_ICONINFORMATION);
return 0;
}
break;
}
Again, this works, but feels like I should be doing it differently.
In particular, when I put the (int) casting here
Code:
if( lParam == (int)g_hwndButton1 )
I felt like I was committing a crime, that the "right" way to do it would be less kludgy.
Some feedback would be appreciated. Thank you.
You Already Got A usable hInstance
Further, why did you use this in your CreateWindow() calls for the hInstance ...
(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE) ?
You already got the hInstance by casting the lParam received in your WM_CREATE handler to a LPCREATESTRUCT, and from that the correct hInstance.