(NOT) 验证 'any key' + 在 Delphi 上按下 DELETE 4

(NOT) Validate 'any key' + DELETE pressed on Delphi 4

我不知道如何捕捉 'any key'(except for CTRL) + 'Deletekey' 新闻。我发现了如何验证 CTRL + 'Deletekey'.

原因是因为我需要做2个动作:

  1. 如果 'CTRL' + 'Deletekey' 被按下。 (已经实现了这个)
  2. 仅当按下 'Deletekey' 时。 (有问题,因为我可以组合 'any key'(except for CTRL) + Deletekey 并且它一直在执行操作 2),但是当且仅当 'Deletekey' 被按下时我才需要执行此操作。

谢谢

编辑:感谢您的回复,我将展示我是如何完成第 1 点的:

上下文优先:我有一个名为 DPaint1KeyUp 的事件,它应该做什么?以图形方式删除绘制的元素(如果按下 DELETE),或者如果同时按下 CTRL + DELETE,则以图形方式从数据库中删除。

procedure TfMyClass.DPaint1KeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  inherited;
  if (Shift = [ssctrl]) and (key = VK_DELETE) then
    //Going to delete graphically and from database

  if (Shift = []) and (key = VK_DELETE) then
    //Going to delete just Graphically
end;

如果我同时按下 CTRL + DELETE,它会完美运行(以图形方式从数据库中删除。

但是,如果我同时按下与 DELETE 的任何组合(CTRL 除外),它会以图形方式删除,WRONG,因为如果我只需要以图形方式删除,我只需要按删除,不是任何其他组合

例如:

@fpiette "A key and DeleteKey simultaneously pressed"

如果您想确保按下的键组合不包含不需要的键,您首先需要使用 GetKeyboardState function.

获取每个键的状态

上面提到的函数 returns 一个包含 256 项的数组,表示 Windows 中任何可能键的状态。

然后您可以遍历上述数组,检查是否使用

按下了某些不需要的键
if (KeyState[I] and ) <> 0 then

由于每个键状态都存储在上述数组中与该特定键的虚拟键值相对应的位置,您可以使用虚拟键指定从上述数组中红色所需的键。

并且由于键状态存储在高位中,我们使用 and 逻辑运算符和 </code> 作为其第二个参数,以便仅读取高位值。</p> <p>如果按键被按下,则该值将为 1,否则将为 0。</p> <p>因此您的代码将如下所示:</p> <pre><code>type //Define set for all possible keys TAllKeys = set of 0..255; ... implementation ... procedure TfMyClass.DPaint1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var KeyState: TKeyboardState; I: Integer; DesiredKeys: TAllKeys; UndesiredKeys: TAllKeys; begin //Use desired keys to set all the keys you want to respoond to DesiredKeys := [VK_DELETE, VK_CONTROL, VK_LCONTROL, VK_RCONTROL, VK_MENU, VK_LMENU, VK_RMENU, VK_SHIFT, VK_LSHIFT, VK_RSHIFT]; //Set undesired keys set as all posible keys substracted by desired keys UndesiredKeys := [0..255] - DesiredKeys; //Retzrieve keyboard state so we can check if one of undesired keys is being pressed down GetKeyboardState(KeyState); //Loop through all keys //NOTE: In modern delphi versions it is possible to loop through elements of individual set using for..in loop // This would allow looping only through undesired keys and not checking every key tro se if it is amongst undesired keys for I := 0 to 255 do begin //If certain key is in undesired keys set check its status if I in UndesiredKeys then begin //If undesired key is pressed down exit the procedure if (KeyState[I] and ) <> 0 then begin //ShowMessage('Non-desired key pressed'); Exit; end; end; end; //If no undesired key is pressed continue with your old code if (Shift = [ssctrl]) and (key = VK_DELETE) then ShowMessage('Ctrl + Delete'); //Going to delete graphically and from database if (Shift = []) and (key = VK_DELETE) then ShowMessage('Delete only'); //Going to delete just Graphically end;

虽然这可能不是最有效的代码,但它可以完成工作。只是不要忘记将您确实想要做出反应的所有所需键添加到 DesiredKeys 集中,这样按下它们就不会退出 OnKeyUp 过程。