views:

416

answers:

2

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.
+14  A: 

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.

Jim McKeeth
This leaves me speechless... I have cracked tougher nuts, but this... aaaahhhh. Thanks for the advice. Much obliged.
Peter Perháč
It happens to all of us. Anytime I am fighting with a bug for more then a little while I know it is going to be something blindingly simple. That is just the way that it works.
Jim McKeeth
A: 

Thanks so much for this - I thought the sound it made was more of a 'Donk' - Searching for 'Ding' led me here.

Ahh, the Donks and Dings of Windows Forms Programming. How we love them...