0

In C# WinForm desktop application Form2, which is login form I have textBox1_KeyDown event:

private void textBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
        LOGIN(); 
    } 
}

Same LOGIN(); function loads Form1 without any Windows 10 sound, for example with button, like this:

 private void button1_Click(object sender, EventArgs e) 
 { 
    LOGIN(); 
 } 

But with pressing Enter key on keyboard, textBox1_KeyDown event loads Form1 with Asterisk Windows 10 sound (played when a popup alert is displayed, like a warning message) or Default Beep sound, (played for multiple reasons with select a parent window before closing the active), or it is Exclamation, which (played when you try to do something that is not supported by OS), according to What Are The Program Events That Are Included In A Sound Scheme?.

I'm not sure which one, this 3 pieces sounds same way, or it is just same audio track, anyway I don't know, how to avoid this sound with entering from keyboard, in LOGIN(); function, form loads this way:

            Form1 objForm1 = new Form1();
            this.Hide();
            objForm1.Show();

Any guide, advice or example would be helpful

  • Try setting `e.Handled = true;` before calling `LOGIN();` – Ron Beyer Oct 03 '18 at 16:12
  • @Ron Beyer , Hello, so I've added `private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; LOGIN(); } }` same result, sound. –  Oct 03 '18 at 16:16

1 Answers1

3

Several ways of doing this, check: Stop the 'Ding' when pressing Enter

I think the best way is to setup the Form.AcceptButton property (to the expected button) and not programming the keydown at the textbox at all, but you could also use the code below if you don't want this way:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //DoYourLogic
        e.Handled = true;
        e.SuppressKeyPress = true;
      }
 }
Felipe Torres
  • 292
  • 2
  • 10
  • Hello, yes works fine, but how to set Form.AcceptButton and Form.CancelButton property, proper way? –  Oct 03 '18 at 16:29
  • I'm not sure if i got your question, but Form.AcceptButton is a property of the form you are using (form2), you just click the properties window and select the button that will be "clicked" when a user presses enter in your form. If you want to set it by code it would be this.AcceptButton = buttonname; basically the "cancelbutton" is the button that is clicked when esc is pressed. If you set acceptbutton you will not need the textbox_keydown code – Felipe Torres Oct 03 '18 at 16:41
  • Ah, ok got it. Thank you for support –  Oct 03 '18 at 16:47