codice:
#include <windows.h>
#define ID_BTN1 101
#define ID_BTN2 102
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT ("Bottoni");
HWND hwnd;
MSG msg;
WNDCLASS wndclass;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("Errore nella chiamata a RegisterClass!"),
szAppName, MB_ICONERROR);
return 0;
}
hwnd = CreateWindow (szAppName, TEXT ("Bottoni in Win API"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
ShowWindow (hwnd, iCmdShow);
UpdateWindow (hwnd);
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HWND hwndButton1;
static HWND hwndButton2;
static int cxChar, cyChar;
switch (message)
{
case WM_CREATE :
cxChar = LOWORD (GetDialogBaseUnits ());
cyChar = HIWORD (GetDialogBaseUnits ());
hwndButton1 = CreateWindow(
TEXT("button"),
TEXT("btn 1"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
cxChar,
cyChar,
20 * cxChar, 7 * cyChar / 4,
hwnd,
(HMENU)ID_BTN1,
((LPCREATESTRUCT)lParam)->hInstance,
NULL);
hwndButton2 = CreateWindow(
TEXT("button"),
TEXT("btn 2"),
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
cxChar,
cyChar * 3,
20 * cxChar, 7 * cyChar / 4,
hwnd,
(HMENU)ID_BTN2,
((LPCREATESTRUCT) lParam)->hInstance,
NULL);
return 0;
case WM_COMMAND :
if ( HIWORD(wParam) == BN_CLICKED )
{
if ( LOWORD(wParam) == ID_BTN1 )
MessageBox(hwnd, TEXT("Ciao dal bottone 1"), TEXT("Ciao"), MB_OK);
else if ( LOWORD(wParam) == ID_BTN2 )
MessageBox(hwnd, TEXT("Ciao dal bottone 2"), TEXT("Ciao"), MB_OK);
}
break ;
case WM_DESTROY :
PostQuitMessage(0);
return 0;
}
return DefWindowProc (hwnd, message, wParam, lParam);
}
Per intercettare i messaggi dei button, devi gestire il messaggio WM_COMMAND nella window procedure.