简体   繁体   中英

Purpose of TranslateMessage and DispatchMessage while setting WH_KEYBOARD_LL hook

I have just begun to learn how to set low level keyboard hooks in Windows using C++.

Here is a small code I have written to get started.

#include <iostream>
#include <windows.h>

HHOOK hook;

LRESULT CALLBACK keyboardHook(int nCode, WPARAM wParam, LPARAM lParam)
{
    KBDLLHOOKSTRUCT *p = (KBDLLHOOKSTRUCT *) lParam;
    std::cout << nCode << " - " << wParam << " - " << p->vkCode << std::endl;
    return CallNextHookEx(hook, nCode, wParam, lParam);
}

int main(int argc, char **argv)
{
    hook = SetWindowsHookEx(WH_KEYBOARD_LL, keyboardHook, NULL, NULL);
    if (hook == NULL) {
        std::cout << "Error " << GetLastError() << std::endl;
        return 1;
    }

    MSG messages;
    std::cout << "Waiting for messages ..." << std::endl;
    while (GetMessage (&messages, NULL, 0, 0))
    {
        std::cout << "Got message" << std::endl;
        TranslateMessage(&messages);
        std::cout << "Translated message" << std::endl;
        DispatchMessage(&messages);
        std::cout << "Dispatched message" << std::endl;
    }
    return 0;
}

I compile this in this manner:

vcvars32.bat
cl /D_WIN32_WINNT=0x0401 foo.cc /link user32.lib

When I execute the code and press A followed by B I get an output like the following:

C:\>foo
Waiting for messages ...
0 - 257 - 13
0 - 256 - 65
0 - 257 - 65
0 - 256 - 66
0 - 257 - 66

Why do I never see Got message in the output? Why does the control never enter the while loop? Can someone help me understand the purpose of GetMessage , TranslateMessage and DispatchMessage here? I have read the documentation, but I guess I am missing something because I fail to understand how they are useful since I am never able to invoke the body of the while loop.

The GetMessage() function waits until a message arrives for one of the windows created by your process. Since you have created no windows, you will receive no messages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM