For example, suppose the user presses the left mouse button. This causes a chain of events:
- The operating system places a WM_LBUTTONDOWN message on the message queue.
- Your program calls the GetMessage function.
- GetMessage pulls the WM_LBUTTONDOWN message from the queue and fills in the MSG structure.
- Your program calls the TranslateMessage and DispatchMessage functions.
- Inside DispatchMessage, the operating system calls your window procedure.
- Your window procedure can either respond to the message or ignore it.
例如,假设用户按下鼠标左键,这个动作将引发连串反应:
1、操作系统将鼠标左键被按下的事件放入事件队列;
2、你的程序(指自己编写的窗口程序)调用
GetMessage函数;
5、在
DispatchMessage函数中,系统又调用了你程序中的window
procedure函数;
6、你的window procedure函数可以回应这条消息,或者忽略这条消息。
配合源码:https://msdn.microsoft.com/zh-cn/library/windows/desktop/ff381409.aspx
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
// Register the window class.
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"Learn to Program Windows", // Window text
WS_OVERLAPPEDWINDOW, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
return 0;
}
ShowWindow(hwnd, nCmdShow);
// Run the message loop.
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
EndPaint(hwnd, &ps);
}
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}