Is it possible using the global keyboard hook (SetWindowsHookEx, WH_KEYBOARD_LL) to change the key it receives (in this case, change it so that it is the modified version of this key that reaches all recipients)?

Tried to do this with the following code, but it didn't work out.

LRESULT CALLBACK llkp(int nCode, WPARAM wParam, LPARAM lParam){ if(nCode==0 && ((PKBDLLHOOKSTRUCT)lParam)->vkCode==VK_SPACE) ((PKBDLLHOOKSTRUCT)lParam)->vkCode=0x5A; //меняем VK_SPACE на клавишу "Z" return CallNextHookEx(hh,nCode,wParam,lParam); } 

I am ready to pay for the decision.

  • If the answer is yes or no, then the answer is yes, it is possible. If you want a more detailed answer - take the trouble to work at least a little bit yourself and give an example of what you have already done, and ask questions on those parts of the code that do not work \ cannot be implemented. - Vladimir Klykov
  • Fine. Already have the code, now lay out. - Ivan Ivanov
  • Is done. So trying to change the key. But nothing comes out. When you press a space, only a space is displayed. - Ivan Ivanov
  • And the interception happens? does the trap work? In general, the code is executed?) And how do you check that the substitution did not work? - Vladimir Klykov
  • Maybe you just want to remap the keys? Type a new keyboard layout? - VTT

2 answers 2

No, it does not work. The point of the hooks is to track events, not to actively influence them. However, a hook allows you to cancel an event by returning a unit from the procedure, so that it does not reach the target application. Then you can generate your own instead with SendInput:

 LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HC_ACTION) { switch (wParam) { case WM_KEYDOWN: PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam; if(p->vkCode == VK_SPACE) { INPUT ip; ip.type = INPUT_KEYBOARD; ip.ki.wScan = 0; ip.ki.time = 0; ip.ki.dwExtraInfo = 0; ip.ki.wVk = 0x5A; //Z ip.ki.dwFlags = 0; // key press SendInput(1, &ip, sizeof(INPUT)); ip.ki.dwFlags = KEYEVENTF_KEYUP; // key release SendInput(1, &ip, sizeof(INPUT)); return 1; } break; } } return CallNextHookEx(NULL, nCode, wParam, lParam); } 

Events generated by SendInput may be perceived by some applications differently from real keyboard events.

  • It is clear: (Thank you very much! - Ivan Ivanov

Nothing to write. To remap the keyboard in the spirit, the user clicks on the "Q" key, and the "W" key should be executed instead of it; you can use the Microsoft Keyboard Layout Creator utility

  • And through the usual global keyboard hook, is it not possible at all? - Ivan Ivanov
  • @IvanIvanov Probably. But I find it difficult to describe it in a go ... - VTT
  • I see, thanks. But in any case your decision does not suit me. I need exactly the code, not the finished utility / program. - Ivan Ivanov