delphi - GetAsyncKeyState "strange"行为

标签 delphi winapi

我有 2 个简单的表单,Form1 和 Form2 (Delphi 7)。 Form1 打开 Form2,我在那里等待特定的组合键 (Ctrl + F2)。一旦我关闭 Form2 并返回到 Form1,我需要检查是否按下了 Ctrl 键。这是一个例子:

表格2

procedure TForm2.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if (Shift = [ssCtrl]) and (Key = VK_F2) then
    ShowMessage('Ctrl + F2 pressed!');
end;

表格1

procedure TForm1.btn1Click(Sender: TObject);
begin
  Try
    Application.CreateForm(TForm2, Form2);
    Form2.ShowModal;
  Finally
    Form2.Release;
    Form2 := nil;
  end;
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  if (GetAsyncKeyState(VK_Control) <> 0) then
    ShowMessage('Ctrl is pressed!');
end;

问题是,每次我在 Form2 上按 Ctrl + F2 时,Ctrl 键似乎卡住了,并且 (GetAsyncKeyState(VK_Control) <> 0) 总是返回 true。

请问您知道发生了什么事(以及如何解决)吗?

最佳答案

你的测试是错误的。来自 documentation :

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState.

要测试按键是否按下,请查看所设置的最高有效位。也就是说,如果值为负数:

if GetAsyncKeyState(VK_Control) < 0 then

我还建议您应该调用 GetKeyState 来获取按下按钮时的状态,而不是 GetAsyncKeyState ,后者是您稍后处理按钮时的状态信息。

关于delphi - GetAsyncKeyState "strange"行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35244767/

相关文章:

delphi - 如何使用 WH_CBT Hook 和 WndProc 捕获发送到窗口的所有消息?

android - FireDac Firebird 和 Android

multithreading - delphi 多线程文件搜索

android - Kitkat 应用程序将在 Lollipop 版本中运行吗

winapi - 调试 WIN32 焦点错误

sockets - 你能在 Windows 上 close()、read() 和 write() 套接字吗?

c# - 我无法使用 C# 禁用 Windows 键

c++ - WinApi - ToUnicode 函数引发访问冲突?

delphi - 无法读取 NetBIOS 状态

winapi - Delphi 中的消息框延迟