次の message.c は、メッセージについての理解を深めるために、ウィンドウが発するメッセージをまとめたアプリケーションです。
#include <windows.h>
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
WNDCLASS wc;
HWND hwnd;
MSG msg;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_BACKGROUND + 1;
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("MESSAGE");
RegisterClass(&wc);
hwnd = CreateWindow(TEXT("MESSAGE"),
TEXT("Windows API Primer"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, 300, 200,
NULL, NULL, hInstance, NULL);
while (GetMessage(&msg, NULL, 0, 0))
{
DispatchMessage(&msg);
}
return msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND label;
RECT rect;
HFONT font;
int x, y;
TCHAR szBuf[256];
switch (msg)
{
case WM_CREATE:
GetClientRect(hwnd, &rect);
font = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
label = CreateWindow(TEXT("STATIC"),
TEXT("♪( ´▽`)"),
WS_CHILD | WS_VISIBLE | SS_CENTER,
(rect.right - 200) / 2,
(rect.bottom - 15) / 2,
200, 15, hwnd, NULL, NULL, NULL);
SendMessage(label, WM_SETFONT, (WPARAM)font, 0);
break;
case WM_SIZE:
GetClientRect(hwnd, &rect);
SetWindowPos (label, HWND_TOP,
(rect.right - 200) / 2,
(rect.bottom - 15) / 2,
0, 0, SWP_NOSIZE);
break;
case WM_KEYDOWN:
if (wParam == VK_RETURN)
SendMessage(label, WM_SETTEXT, 0,
(LPARAM)TEXT("Enter key has been pressed."));
else
SendMessage(label, WM_SETTEXT, 0,
(LPARAM)TEXT("A key has been pressed."));
break;
case WM_RBUTTONDOWN:
SendMessage(label, WM_SETTEXT, 0,
(LPARAM)TEXT("Right button was clicked."));
break;
case WM_LBUTTONDOWN:
SendMessage(label, WM_SETTEXT, 0,
(LPARAM)TEXT("Left button was clicked."));
break;
case WM_MOUSEMOVE:
x = LOWORD(lParam);
y = HIWORD(lParam);
wsprintf(szBuf, TEXT("Mouse has moved to %d %d"), x, y);
SendMessage(label, WM_SETTEXT, 0, (LPARAM)szBuf);
break;
case WM_MOVE:
x = LOWORD(lParam);
y = HIWORD(lParam);
wsprintf(szBuf, TEXT("Window has moved to %d %d"), x, y);
SendMessage(label, WM_SETTEXT, 0, (LPARAM)szBuf);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
右クリック | Right button was clicked. |
左クリック | Left button was clicked. |
キーボードのキーを押す | A key has been pressed. |
エンターキーを押す | Enter key has been pressed. |
マウスを移動する | Mouse has moved to x point y point |
ウィンドウを移動する | Window has moved to x point y point |