delphionkeydowndelphi-10.1-berlinkeypreview

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


A. Create a VCL Forms Application.

B. Put a TListBox on the form and fill in some items at design-time, for example:

enter image description here

C. Set the Form's KeyPreview property to True:

enter image description here

D. In the Form's OnKeyDownevent-handler write this code:

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. Run the program and select Item5 by clicking on it:

enter image description here

Now ListBox1 has the focus.

F. Now press the BACKSPACE key. Supposedly, setting Key := 0; in the Form's OnKeyDownevent-handler should block the BACKSPACE key from being processed by the ListBox1 control. But this does not work, as you can see: The BACKSPACE key caused to change the selection from Item5 to Item1:

enter image description here

So how can I prevent the BACKSPACE key from being processed in the focused ListBox control and to change the ListBox's selection?

Delphi 10.1 Berlin Update 2
Windows 7 x64 SP1


Solution

  • Use the OnKeyPress event instead:

    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;
    

    You can't always block everything in OnKeyDown.