John Barrat
John Barrat

Reputation: 830

Cannot close a Delphi form without causing a Beep

I have a PopUpform containing 1 edit box. I call ShowModal from the main form and using Enter and Escape in the PopUpform.keyDown event to close the PopUp and set the appropriate modal result when it returns to the main form.

Opening the form and closing it when the edit box has focus causes a beep. If the editbox doesn't have focus the form closes silently. What can I do to prevent the beep when the edit box has focus?

Upvotes: 1

Views: 324

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108948

Typically, a dialog box contains an OK and a Cancel button, the Enter key "clicks" the OK button and the Escape key "clicks" the Cancel button.

To manage the dialog box, you set the OK button's Default property to True and the Cancel button's Cancel property to True. In addition, these buttons should also have the appropriate ModalResult values:

  • btnOK

    Caption = "OK"
    Default = True
    ModalResult = mrOk

  • btnCancel

    Caption = "Cancel"
    Cancel = True
    ModalResult = mrCancel

Then you show the dialog using ShowModal:

frm := TFrogPropertiesFrm.Create(Self);
try
  if frm.ShowModal = mrOk then
    UpdateFrogProperties;
finally
  frm.Free;
end;

Notice that Enter automatically "clicks" the OK button and that Escape automatically "clicks" then Cancel button. Also notice that the defaultness of the OK button is indicated by a thick border.

If, instead, you have a dialog box with only a single button, this is typically captioned Close and should have both Default and Cancel set to True. Its modal result can be mrClose, for instance.


This being said, if your form really doesn't have any suitable buttons and you do

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case Key of
    VK_RETURN:
      ModalResult := mrOk;
    VK_ESCAPE:
      ModalResult := mrCancel;
  end;
end;

you can silence the beep by doing

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if Key = Chr(VK_RETURN) then
    Key := #0;
end;

Upvotes: 2

Related Questions