A. Create a VCL Forms Application.
B. Put a TListBox on the form and fill in some items at design-time, for example:
C. Set the Form's KeyPreview
property to True
:
D. In the Form's OnKeyDown
event-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:
Now ListBox1 has the focus.
F. Now press the BACKSPACE key. Supposedly, setting Key := 0;
in the Form's OnKeyDown
event-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:
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
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
.