Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop the 'Ding' when pressing Enter

It works for me:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

    //Se apertou o enter
    if (e.KeyCode == Keys.Enter)
    {
        //enter key is down

        this.doSomething();

        e.Handled = true;
        e.SuppressKeyPress = true;

     }

 }

The SuppressKeyPress is the really trick. I hope that help you.


Check out the Form.AcceptButton property. You can use it to specify a default button for a form, in this case for pressing enter.

From the docs:

This property enables you to designate a default action to occur when the user presses the ENTER key in your application. The button assigned to this property must be an IButtonControl that is on the current form or located within a container on the current form.

There is also a CancelButton property for when the user presses escape.


Try

textBox.KeyPress += new KeyPressEventHandler(keypressed);

private void keypressed(Object o, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.Handled = true; //this line will do the trick
    }
}

Just add e.SuppressKeyPress = true; in your "if" statement.

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //If true, do not pass the key event to the underlying control.
        e.SuppressKeyPress = true;  //This will suppress the "ding" sound.*/

        // Perform search now.
    }
}

You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle

  private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
        {
            e.Handled = true;
            button1.PerformClick();
        }
    }

and say peace to the 'Ding'


Use SuppressKeyPress to stop continued processing of the keystroke after handling it.

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

   private void EntryTextBox_KeyDown(object sender, KeyEventArgs e)
   {
      if(e.KeyCode == Keys.Enter)
      {
         e.Handled = true;
         e.SuppressKeyPress = true;
         // do some stuff

      }
      else if(e.KeyCode == Keys.Escape)
      {
          e.Handled = true;
          e.SuppressKeyPress = true;
          // do some stuff

      }
   }

   private void EntryTextBox_KeyUp(object sender, KeyEventArgs e)
   {
      if(e.KeyCode == Keys.Enter)
      {
         // do some stuff

      }
      else if(e.KeyCode == Keys.Escape)
      {
         // do some stuff

      }
   }
}