views:

133

answers:

3

I have a default button on a form that has a TSpinEdit control on it. When the TSpinEdit control has the focus and the user presses the Enter key, instead of the default button getting clicked, the user just hears a system beep because the Enter key is invalid for a TSpinEdit.

Normally, to avoid the beep, I would use the OnKeyPress event and set the Key := 0 to skip the key press. I could then execute the click method on the default button. However, in this case, OnKeyPress doesn't fire because the Enter key is not valid.

OnKeyDown fires, but when I set Key := 0 there, it doesn't stop the system beep.

So, how do I disable the system beep when pressing the Enter key on a TSpinEdit control?

I'm on Delphi 5, and they didn't include the source for Spin.pas.

+2  A: 

Try this one

//Disable system beep
SystemParametersInfo(SPI_SETBEEP, 0, nil, SPIF_SENDWININICHANGE); 

//Enable system beep
SystemParametersInfo(SPI_SETBEEP, 1, nil, SPIF_SENDWININICHANGE); 
Bharat
@Bharat, thanks for the great info, but I still want to hear the beeps for the other invalid keys, so if I wait until the OnKeyDown event fires before I disable the system beep, it doesn't seem to prevent the beep.
Marcus Adams
Cool hack. I did not know about this.
Warren P
+3  A: 

You have to descend from TSpinEdit and override IsValidChar to avoid the MessageBeep call or KeyPress to avoid IsValidChar.

François
This is what I did, of course, though thanks to Uwe for helping me find the source!
Marcus Adams
+1  A: 

Set KeyPreview = True on your form and add the following code to the form's keypress event:

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
  if SpinEdit1.Focused and (Key = #13) then
  begin
    Key := #0; // Cancels the keypress
    Perform(CM_DIALOGKEY, VK_RETURN, 0); // Invokes the default button
  end;
end;
Cobus Kruger