How to monitor the keyboard above all other applications and then send other keys to them instead

故事扮演 提交于 2019-12-03 21:18:40

Part of the solution can be use a Keyboard Hook (WH_KEYBOARD_LL) to capture a special key combination or a single key and then use the keybd_event function to send (replace) another keystroke.

Try this sample code which intercepts the VK_UP key and send a S

var
 hhk: HHOOK;


function CBT_FUNC(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;


type
  PKBDLLHOOKSTRUCT = ^TKBDLLHOOKSTRUCT;
  TKBDLLHOOKSTRUCT = record
    vkCode: cardinal;
    scanCode: cardinal;
    flags: cardinal;
    time: cardinal;
    dwExtraInfo: Cardinal;
  end;
  PKeyboardLowLevelHookStruct = ^TKeyboardLowLevelHookStruct;
  TKeyboardLowLevelHookStruct = TKBDLLHOOKSTRUCT;

var
 LKBDLLHOOKSTRUCT: PKeyboardLowLevelHookStruct;
begin
   case nCode of
     HC_ACTION:
     begin
       LKBDLLHOOKSTRUCT := PKeyboardLowLevelHookStruct(lParam);
        if (LKBDLLHOOKSTRUCT^.vkCode = VK_UP)  then
        begin

          if (wParam=WM_KEYUP) or (wParam=WM_SYSKEYUP)then
           keybd_event( Ord('S'), 0, KEYEVENTF_KEYUP, 0)
          else
           keybd_event( Ord('S'), 0, 0, 0);

          Exit(1); //eat the key
        end;
     end;
   end;
  Result := CallNextHookEx(hhk, nCode, wParam, lParam);
end;

Procedure InitHook();
begin
  hhk := SetWindowsHookEx(WH_KEYBOARD_LL, @CBT_FUNC, 0, 0);
  if hhk=0 then RaiseLastOSError;
end;


Procedure KillHook();
begin
  if (hhk <> 0) then
    UnhookWindowsHookEx(hhk);
end;


initialization
  InitHook();

finalization
  KillHook();
end.

Before to use this kind of hook remember read the documentation, specifically the remarks section.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!