Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Windows 'Ding' when Enter is pressed in TextBox with OnKeyUp

If a user hits enter in a windows forms textbox with a KeyUp Event, windows sounds a beep or ding. I could not determine why this happens and how I could avoid this.

Any help would be appreciated.

like image 645
ibram Avatar asked Jul 12 '11 07:07

ibram


4 Answers

Actual solution for getting rid of the sound:

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        e.SuppressKeyPress = true;
    }
}
like image 78
Camilo Martin Avatar answered Oct 14 '22 17:10

Camilo Martin


Here is the actual answer:

    Private Sub myTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles myTextBox.KeyPress
    If Asc(e.KeyChar) = 13 Then
        e.Handled = True
    End If
End Sub

This eats the key press, which prevents the ding.

like image 37
Rogala Avatar answered Oct 14 '22 16:10

Rogala


I imagine this is caused by a combination of:

  • MultiLine = false
  • No default button on the form

because single-line textboxes forward the enter key to the default button. The ding is generated when a default button can't be found.

like image 20
Ben Voigt Avatar answered Oct 14 '22 15:10

Ben Voigt


After some hours digging for a solution, I just got a workaround, but not a real solution for this problem. Now I'm using KeyDown instead.

private void tbSearch_KeyDown( object sender, KeyEventArgs e )
{
    if ( e.KeyCode == Keys.Enter )
    {
         e.Handled = true;
         // Call Button event
         //btnSearch_Click( sender, EventArgs.Empty );
         // cleaner code. Thanks to Hans.
         btnSearch.PerformClick();
    }
}

And a useful suggestion to all developers: Don't test your applications whit mute sound. ;-)

like image 40
ibram Avatar answered Oct 14 '22 15:10

ibram