使用TForm.OnKeyDown中的KeyPreview进行密钥处理不适用于TListBox

时间:2016-12-03 20:27:30

标签: delphi onkeydown delphi-10.1-berlin keypreview

一个。创建VCL表单应用程序。

B中。将TListBox放在表单上并在设计时填写一些项目,例如:

enter image description here

℃。将表单的KeyPreview属性设置为True

enter image description here

d。在Form的OnKeyDown事件处理程序中编写此代码:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_BACK then
  begin
    if ListBox1.Focused then
    begin
      Key := 0;
      CodeSite.Send('ListBox1 is focused!');
    end;
  end;
end;

电子。运行程序并通过单击选择Item5:

enter image description here

现在ListBox1具有焦点。

F。现在按BACKSPACE键。据推测,在Form的Key := 0;事件处理程序中设置OnKeyDown应该阻止ListBox1控件处理BACKSPACE键。但是这不起作用,正如您所看到的:BACKSPACE键导致将选择从Item5更改为Item1:

enter image description here

那么如何防止在聚焦的ListBox控件中处理BACKSPACE键并更改ListBox的选择?

Delphi 10.1 Berlin Update 2
Windows 7 x64 SP1

1 个答案:

答案 0 :(得分:2)

改为使用OnKeyPress事件:

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = #8 then
  begin
    if ListBox1.Focused then
    begin
      Key := #0;
      CodeSite.Send('ListBox1 is focused!');
    end;
  end;
end;

您无法始终阻止OnKeyDown中的所有内容。