views:

739

answers:

3

Hello,

I can't figure out how to capture the delete key 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

+5  A: 

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.

mghie
+5  A: 

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.

Ville Krumlinde
You can also delete text by selecting it and then typing new text.
Greg Hewgill
@Greg Hewgill, it is easily avoidable. I can check what part of text is selected in the KeyPress event before letting user to write something.
+2  A: 

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

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word; Shift:
    TShiftState);
begin
  if Key = VK_DELETE then begin
    Beep;
    Key:= 0;
  end;
end;
Serg