TForm.OnKeyDown 中使用 KeyPreview 的键处理不适用于 TListBox

Key handling with KeyPreview in TForm.OnKeyDown does not work with TListBox

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

乙。在窗体上放置一个 TListBox 并在设计时填写一些项目,例如:

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

D.在表单的 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;

E. 运行 程序和 select 通过单击项目 5:

现在 ListBox1 获得了焦点。

F.现在按 BACKSPACE 键。据推测,在表单的 OnKeyDown 事件处理程序中设置 Key := 0; 应该阻止 BACKSPACE 键被 ListBox1 控件处理。但这不起作用,如您所见:BACKSPACE 键导致将 selection 从 Item5 更改为 Item1:

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

Delphi 10.1 柏林更新 2
Windows 7 x64 SP1

改为使用 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 中的所有内容。