Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a NumericUpDown from playing 'Ding' sound on EnterKeyPress

I have a few NumericUpDown controls on my form, and everytime I hit the enter key while it is active, it plays this horrible DING noise, right in my ears. It plays if I don't handle the KeyPress event, and it plays if I do handle the KeyPress event, with or without e.Handled = true:

myNumericUpDown.KeyPress += myNumericUpDown_KeyPress;

private void myNumericUpDown_KeyPress(object sender, EventArgs e)
{
    if (e.KeyChar == 13)
    {
        e.Handled = true; //adding / removing this has no effect
        myButton.PerformClick();
    }
}

And I don't think it is happening because I am handling it, as if I don't register the event (removing the first line above), it still plays the noise.

like image 524
Shadow Avatar asked Dec 19 '22 08:12

Shadow


1 Answers

Use KeyDown() and SuppressKeyPress, but click the button in KeyUp():

    private void myNumericUpDown_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.Handled = e.SuppressKeyPress = true;
        }
    }

    private void myNumericUpDown_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            e.Handled = e.SuppressKeyPress = true;
            myButton.PerformClick();
        }
    }

*If you set the Forms AcceptButton Property to "myButton", then NO code is needed at all!

like image 57
Idle_Mind Avatar answered Jan 26 '23 00:01

Idle_Mind