Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top