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

自闭症网瘾萝莉.ら 提交于 2020-01-01 07:08:00

问题


I am building an multimedia console based on an old computer running Win7.

I want to control the players with a numeric keyboard. I can't use the common media control devices because they respond only to windows media player. I will use the KVM Player, Winamp and others. So each one has it's own set of keyboard shortcuts for play, pause, foward, volume etc.

For that I am thinking of building a Delphi application that detects the foreground application and gets from a database the shortcuts this application uses.

When I use the numeric keyboard (the size of a regular remote control) and press 5 for play, my application could detect it and send to the OS the P key if I am using Winamp or Space if I am using Media Player Classic.

What functions should I use to first grab the pressed key and then send a different key?


回答1:


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.



来源:https://stackoverflow.com/questions/13940590/how-to-monitor-the-keyboard-above-all-other-applications-and-then-send-other-key

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