我已阅读msdn链接,并尝试在以下keylogger-code中使用 GetMessage() 函数。
在下面附加的最小版本的程序中,如果我按下键盘或调整窗口大小,为什么 GetMessage() 不释放并打印“新消息”?
#include <stdio.h>
#inlcude <stdlib.h>
#inlcude <windows.h>
int main() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) != 0) {
printf("\nnew message!");
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
更新:正如你提到的,我给了进程一个窗口(句柄),并且在我将 GetMessage() 保存在 WinMain 期间它工作正常。因为应该有其他功能,所以我需要将 GetMessage() 外包给它自己的线程,如下所示。不幸的是,GetMessage() 函数再次挂起,即使我指定了应在其参数中接收消息的窗口句柄。有什么提示可以让我进一步了解此功能吗?
void control(HWND hwnd) {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) != 0) {
printf("\nnew message!");
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// window class creation
const char window_name[] = "myWindow";
WNDCLASSEX wc;
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = window_name;
wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
// register the class
if(!RegisterClassEx(&wc)) {
MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// window creation
HWND hwnd;
hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, window_name, "The Window Title", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL);
if(hwnd == NULL) {
MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}
// show window
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// threading
HANDLE thread
thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE*) control, hwnd, 0, NULL);
WaitForSingleObject(thread, INFINITE);
return 0;
}