Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the ding sound when Escape is pressed while a TEdit is focused?

In code I have developed some years ago I have been using this a lot to close the current form on pressing the Escape key at any moment:

procedure TSomeForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
    if key = #27 then close;
end;

This behaviour is defined for the TForm. The form's KeyPreview property is be set to True to let the form react to key presses before any other components. It all works perfectly well for the best part of the program, however, when the Escape key is pressed while a TEdit component is focused a sound (a ding sound used by Windows to signify invalid operation) is issued. It still works fine but I have never quite managed to get rid of the sound.

What's the problem with this?


Steps to recreate:

  • new VCL Forms application, set the form's KeyPreview to true
  • on the Events tab double-click the onKeyPress event and enter dummy code:

    if key=#27 then ;

  • add a TListBox, TCheckBox, TEdit to the form and run the application

  • in the application try pressing Esc and NOTHING happens, as specified by the dummy code
  • focus the TEdit and press Esc. Nothing happens but the sound is played.
like image 414
Peter Perháč Avatar asked Apr 20 '09 21:04

Peter Perháč


1 Answers

You get the ding because you left the ESC in the input. See how Key is a var? Set it to #0 and you eliminate the ding. That removes it from further processing.

procedure TSomeForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
    if key = #27 then 
    begin
      key := #0;
      close;
    end;
end;

KeyPreview is just that, a preview of what will be passed to the controls unless you stop it.

like image 138
Jim McKeeth Avatar answered Oct 23 '22 11:10

Jim McKeeth