delphi - SendInput 与 keybd_event

标签 delphi keyboard-events sendinput

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;

最佳答案

问题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;

关于delphi - SendInput 与 keybd_event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662637/

相关文章:

JavaScript 按键处理

delphi - 为什么 SendInput Ctrl+V 在 Outlook 中不起作用?

delphi - 我可以在Delphi 7中使用PUT和DELETE发送请求吗?

sql - 如何监控我的 Delphi 应用程序执行的 SQL?

delphi - Delphi 7中处理海量文本文件数据的最佳解决方案

delphi - 如何在同一项目组中的项目之间共享单元?

java - 读取前刷新/清除 System.in (stdin)

c# - 尝试使用ProcessCmdKey在MDI父/子窗体和其他窗体中实现全局快捷键

c++ - SendInput On C++ 不显示下划线

c++ - SendInput() 不等于在 C++ 中手动在键盘上按键?