Capturing a 'delete' key press

30,723

Solution 1

You should handle the OnKeyDown instead of the OnKeyPress event. If you do that then VK_DELETE should work for you. Note that the parameter for OnKeyDown and OnKeyUp is a Word, not a Char as for OnKeyPress.

Solution 2

Mghie has the correct answer, here is a sample:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
   if Key=VK_DELETE then
     showmessage('Delete key was pressed');
end;

Note that the user can also delete text using cut-to-clipboard so you may need to handle that as well.

Solution 3

You can use OnKeyDown event to filter the undesired Delete key pressed:

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift:
    TShiftState);
begin
  if Key = VK_DELETE then begin
    Beep;
    Key:= 0;
  end;
end;
Share:
30,723
user1651105
Author by

user1651105

Updated on July 09, 2022

Comments

  • user1651105
    user1651105 almost 2 years

    I can't figure out how to capture the Deletekey press. I found out that in ASCII code table, it is at 127 place, but if (Key = #127) then got me nowhere.

    Then I checked the value of VK_DELETE which was 47. Tried to use that, but it didn't work.

    The KeyPreview := true is set in my form.

    I tried to add the ShowMessage(IntToStr(Ord(Key))) to the Forms KeyPress event, but I never got the message popup while clicking the Delete key.

    I need to handle the Delete key press in dynamicaly created Edit fields. I want to control what part of the text user can erase in that field, and I know how to handle the text deletion using Backspace key, now need to figure out how to do it with Delete key.

    Thanks