Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stop Window Error Sound When Typing 'Enter' or 'Esc'

Tags:

c#

winforms

I have a form with a single text box on it. No other controls. Whenever I type the 'Enter' key or the 'Esc' key, the form functions as I desire; but I hear that horrible Windows error sound. The code looks similar to the following...

public class EntryForm: Form
{
  public EntryForm()
  {
  }

  private void EntryTextBox_KeyUp(object sender, KeyEventArgs e)
  {
    if(e.KeyCode == Keys.Enter)
    {
      // do some stuff
      Hide(); // I've also used DialogResult = DialogResult.OK here
      e.Handled = true;
    }
    else if(e.KeyCode == Keys.Escape)
    {
      Hide(); // I've also used DialogResult = DialogResult.Cancel here
      e.Handled = true;
    }
  }
}

I can 'hack' it and make the noise stop by adding the following code to the form's constructor.

AcceptButton = new Button();
CancelButton = new Button();

As I stated this causes the sound to not play, but I think this is bad form; especially since I don't need a button on the form.

Anyone know why this is the behavior and if there is a cleaner way to stop the error sound from playing?

like image 999
John Kraft Avatar asked Dec 30 '09 22:12

John Kraft


1 Answers

In the KeyDown event, set e.Handled = true and e.SuppressKeyPress = true.

like image 177
Andrew Avatar answered Nov 09 '22 22:11

Andrew