How to send Ctrl/Shift/Alt + Key combinations to an application window? (via SendMessage)

后端 未结 5 640
日久生厌
日久生厌 2021-02-13 18:24

I can successfully send any single key message to an application, but I don\'t know how to send combinations of keys (like Ctrl+F12, Shift+

5条回答
  •  攒了一身酷
    2021-02-13 19:17

    The OP is now saying he needs to send input to minimized applications without activating them. This is not possible to do reliably in any way, including even with specialized hardware. I've worked in automation. It just isn't possible.

    Sending input to minimized applications is, in fact, possible, not sure about mouse input, but keyboard input works just fine. Taking idea in a previous answer here's what I was able to accomplish (code is in Delphi, but it's pretty simple, so you can translate it to your required language):

    procedure SendKeys(const Win : HWND; const Key,sKey: Cardinal);
    var
      thrID : Cardinal;
      KB : TKeyBoardState;
    begin
      if sKey <> 0 then
      begin
        thrID := GetWindowThreadProcessId(win,nil);
        GetKeyboardState(KB);
        AttachThreadInput(GetCurrentThreadID, thrID, True);
        KB[sKey] := KB[sKey] or $80;
        SetKeyboardState(KB);
      end;
      SendMessage(Win,WM_KEYDOWN,Key,0);
      SendMessage(Win,WM_KEYUP,Key,0);
      if sKey <> 0 then
      begin
        KB[sKey] := 0;
        SetKeyBoardState(KB);
        AttachThreadInput(GetCurrentThreadId, thrID, False);
      end;
    end;
    

    [Win] must be the control to receive the input, not its parent form etc. [Key] is a key to be pressed; [sKey] is an alternative key to be pressed while pressing [Key] such as CTRL/SHIFT (ALT is transferred through message itself, see MSDN WM_KEYDOWN reference for details).

    Sending a sole keystroke is fairly simple, you just do the sendmessage and it's done, but if you need to something like CTRL+SPACE here's where it gets complicated. Each thread has its own KeyboardState, altering KeyboardState in your own app will not affect another unless you join their thread inputs by AttachThreadInput function. When application processes WM_KEYDOWN message it also tests current shift states (CTRL/SHIFT) by calling GetKeyboardState function (ALT key can be sent through the additional parameter of WM_KEYDOWN message) and that's when attached thread input comes into play.

提交回复
热议问题