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>
HHOOK kHook;
LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
switch (wParam)
{
case WM_KEYDOWN:
return -1;
case WM_SYSKEYDOWN:
return -1;
}
return CallNextHookEx(kHook, nCode, wParam, lParam);
}
void sendString(std::wstring message)
{
std::wstring msg = message;
for (auto ch : msg)
{
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);
sendString(L"Some String");
UnhookWindowsHookEx(kHook);
}
CodePudding user response:
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.
CodePudding user response:
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.