C语言 GetMessage() hanging up



我已经阅读了msdn链接,并尝试在以下键盘记录器代码中接近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;
    }

您的程序没有附加窗口。当您使用printfmain时,我假设它是一个控制台程序。在这种情况下,Windows消息(如键盘事件(由托管您自己的程序的控制台处理,然后该控制台提供您的stdin并显示它从stdout/stderr获得的内容。

为了能够使用消息循环,常见的方法是首先创建一个窗口。如果不这样做,您只会从另一个知道它的程序获得明确发送到线程的消息。

对不起,这只是提示,但完整而详细的解释将远远超出 SO 答案......

最新更新