应用程序为了获取源源不断的消息,就需要调用函数 GetMessage 来实现。因为所有在窗 口上的输入消息,都会放到应用程序的消息队列里,然后再发送给窗口回调函数处理。 函数 GetMessage 声明如下:
WINUSERAPI BOOL
WINAPI
GetMessageA(
out LPMSG lpMsg,
in_opt HWND hWnd,
in UINT wMsgFilterMin,
in UINT wMsgFilterMax);
WINUSERAPI BOOL
WINAPI
GetMessageW(
out LPMSG lpMsg,
in_opt HWND hWnd,
in UINT wMsgFilterMin,
in UINT wMsgFilterMax);
#ifdef UNICODE
#define GetMessage GetMessageW
#else
#define GetMessage GetMessageA
#endif // !UNICODE
- lpMsg 是从线程消息队列里获取到的消息指针。
- hWnd 是想获取那个窗口的消息,当设置为 NULL 时是获取所有窗口的消息。
- wMsgFilterMin 是获取消息的 ID 编号最小值,如果小于这个值就不获取回来。
- wMsgFilterMax 是获取消息的 ID 编号最大值,如果大于这个值就不获取回来。
函数返回值可能是 0,大于 0,或者等于-1。如果成功获取一条非 WM_QUIT 消息时,就 返回大于 0 的值;如果获取 WM_QUIT 消息时,就返回值 0 值。如果出错就返回-1 的值。
调用这个函数的例子如下:
//主程序入口
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
MSG msg;
HACCEL hAccelTable;
// 加载全局字符串。
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_TESTWIN, szWindowClass, MAX_LOADSTRING);
MyReg isterClass(hInstance);
// 应用程序初始化:
if (!Init Instance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTab le = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_TESTWIN));
// 消息循环:
BOOL bRet;
while ( (bRet = GetMessage(&msg, NULL, 0, 0)) != 0)
{
if (bRet == -1)
{
//处理出错。
}
else if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
- 第28行就是获取所有窗口的消息回来。