简体   繁体   中英

SendInput can't send keyboard inputs when the LowLevelKeyboardProc hook is enabled on Windows

I made the program that will block every keyboard button on Windows using WinAPI and send a string using SendInput function but I couldn't find a way to make SendInput send keyboard keys while the hook is enabled. Here is my code:

#include <Windows.h>
#include <vector>
#include <string>

HHOOK kHook;
KBDLLHOOKSTRUCT kbdStruct;

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    kbdStruct = *((KBDLLHOOKSTRUCT*)lParam);
    if (nCode == HC_ACTION)
    {
        if (kbdStruct.flags != LLKHF_INJECTED)
        {
            switch (wParam)
            {
            case WM_KEYDOWN:
                return -1;
            case WM_SYSKEYDOWN:
                return -1;
            }
            return CallNextHookEx(kHook, nCode, wParam, lParam);
        }
    }
}

void sendString(std::wstring message)
{
    for (auto ch : message)
    {
        Sleep(250);
        std::vector<INPUT> vec;
        INPUT input = { 0 };
        input.type = INPUT_KEYBOARD;
        input.ki.dwFlags = KEYEVENTF_UNICODE;
        input.ki.wScan = ch;
        vec.push_back(input);

        input.ki.dwFlags |= KEYEVENTF_KEYUP;
        vec.push_back(input);

        SendInput(vec.size(), vec.data(), sizeof(INPUT));
    }
}
int main()
{
    kHook = SetWindowsHookExW(WH_KEYBOARD_LL, LowLevelKeyboardProc, NULL, 0);
    MSG msg;
    while (GetMessageW(&msg, NULL, 0, 0))
    {
        sendString(L"Some String");
    }
}

According to the documentation , there's a flag in KBDLLHOOKSTRUCT ( LLKHF_INJECTED ) which tells you whether the event was 'injected', so, with any luck, you can test that and pass it on if it is.

Note also that you hook proc is not doing quite the right thing. If you read this page , you will see that you should always pass the event on if nCode is negative, so you should add that in.

I shudder to think why you want to do any of this, but hey.

Instead of swallowing all keyboard input (which clearly conflicts with your intention of sending some keyboard input), try filtering input instead.

Right now your keyboard hook stops all input, including the messages you send in sendString . Change your keyboard hook so it understands what messages are allowed to pass.

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