简体   繁体   English

在 Windows 上启用 LowLevelKeyboardProc 挂钩时,SendInput 无法发送键盘输入

[英]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.我制作了一个程序,它将使用 WinAPI 阻止 Windows 上的每个键盘按钮,并使用 SendInput 函数发送一个字符串,但我找不到在启用钩子时让 SendInput 发送键盘键的方法。 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.根据文档KBDLLHOOKSTRUCT ( LLKHF_INJECTED ) 中有一个标志,它告诉您事件是否被“注入”,因此,如果运气好的话,您可以对其进行测试并传递它。

Note also that you hook proc is not doing quite the right thing.另请注意,您 hook proc 并没有做正确的事情。 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.如果您阅读此页面,您会发现如果nCode为负数,您应该始终传递事件,因此您应该添加它。

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 .现在,您的键盘钩子会停止所有输入,包括您在sendString中发送的消息。 Change your keyboard hook so it understands what messages are allowed to pass.更改您的键盘挂钩,以便它了解允许传递的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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