4

MSDN 声明 keybd_event 已被 SendInput 取代。在重写期间,我切换到使用 SendInput ...这很好,除非尝试发送 Alt 键组合。在 Win7 64 位系统上(尚未在其他地方尝试过),发送 Alt 键会导致在目标应用程序中击键出现之前很长的延迟。

任何想法为什么?还是我做错了什么?现在,我回到了 keybd_event——下面的第二个版本。

//Keyboard input from this version appears only after a ~4-5 second
//time lag...
procedure SendAltM;
var
  KeyInputs: array of TInput;
  KeyInputCount: Integer;
  //--------------------------------------------
  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    Inc(KeyInputCount);
    SetLength(KeyInputs, KeyInputCount);
    KeyInputs[KeyInputCount - 1].Itype := INPUT_KEYBOARD;
    with  KeyInputs[KeyInputCount - 1].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := KEYEVENTF_EXTENDEDKEY;
      dwFlags := Flags or dwFlags;
      time := 0;
      dwExtraInfo := 0;
    end;
  end;
begin
  KeybdInput(VK_MENU, 0);                 // Alt
  KeybdInput(Ord('M'), 0);                 
  KeybdInput(Ord('M'), KEYEVENTF_KEYUP);   
  KeybdInput(VK_MENU, KEYEVENTF_KEYUP);   // Alt
  SendInput(KeyInputCount, KeyInputs[0], SizeOf(KeyInputs[0]));
end;


//Keyboard input from this version appears immediately...
procedure SendAltM;
begin
  keybd_event( VK_MENU, MapVirtualkey( VK_MENU, 0 ), 0, 0);
  keybd_event( Ord('M'), MapVirtualKey( Ord('M'),0), 0, 0);
  keybd_event( Ord('M'), MapVirtualKey( Ord('M'),0), KEYEVENTF_KEYUP, 0);
  keybd_event( VK_MENU, MapVirtualkey( VK_MENU, 0 ), KEYEVENTF_KEYUP, 0);
end;
4

2 回答 2

8

问题 1

你没有初始化KeyInputCount。所以它的值是不确定的。KeybdInput在第一次调用之前将其设置为零。或者只是摆脱它并使用它Length(KeyInputs)

问题 2

你的设置dwFlags不正确。不包括KEYEVENTF_EXTENDEDKEY. 您没有将其包含在调用的代码中keybd_event,也不应将其包含在SendInput.

更正的代码

这个版本有效。

procedure SendAltM;
var
  KeyInputs: array of TInput;
  //--------------------------------------------
  procedure KeybdInput(VKey: Byte; Flags: DWORD);
  begin
    SetLength(KeyInputs, Length(KeyInputs)+1);
    KeyInputs[high(KeyInputs)].Itype := INPUT_KEYBOARD;
    with  KeyInputs[high(KeyInputs)].ki do
    begin
      wVk := VKey;
      wScan := MapVirtualKey(wVk, 0);
      dwFlags := Flags;
    end;
  end;
begin
  KeybdInput(VK_MENU, 0);                 // Alt
  KeybdInput(Ord('M'), 0);
  KeybdInput(Ord('M'), KEYEVENTF_KEYUP);
  KeybdInput(VK_MENU, KEYEVENTF_KEYUP);   // Alt
  SendInput(Length(KeyInputs), KeyInputs[0], SizeOf(KeyInputs[0]));
end;
于 2013-09-06T16:53:52.673 回答
3

这样你就可以使用keybd_event

keybd_event( VK_MENU, MapVirtualkey( VK_MENU, 0 ), KEYEVENTF_EXTENDEDKEY or 0, 0);
  keybd_event( Ord('M'), MapVirtualKey( Ord('M'),0), KEYEVENTF_EXTENDEDKEY or 0, 0);
  keybd_event( Ord('M'), MapVirtualKey( Ord('M'),0), KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
  keybd_event( VK_MENU, MapVirtualkey( VK_MENU, 0 ), KEYEVENTF_EXTENDEDKEY or KEYEVENTF_KEYUP, 0);
于 2016-02-17T12:50:52.093 回答