简体   繁体   中英

Cannot disable beep sound on textbox keydown event

Below is my code for disabling beep sound when I press "Enter" on textbox KeyDown() event:

if (e.KeyCode == Keys.Enter)
{
    e.SuppressKeyPress = true;
    SaveData();
    e.Handled = true;
}

But it keeps beeping when I press "Enter" on textbox. What am I doing wrong?

From your comments, showing a MessageBox will interfere with your setting of the SuppressKeyPress property.

A work-around is to delay the showing of the MessageBox until after the method is completed:

void TextBox1_KeyDown(object sender, KeyEventArgs e) {
  if (e.KeyCode == Keys.Enter) {
    e.SuppressKeyPress = true;
    this.BeginInvoke(new Action(() => SaveData()));
  }
}

EDIT

Please note that the answer provided by LarsTech ( below ) is a far better approach.


Sorry, I just realised that you have a MessageBox displaying.

What you can do is have a Timer and have it fire off the SaveData() method.

private void Timer1_Tick(System.Object sender, System.EventArgs e)
{
    Timer1.Enabled = false;
    SaveData();
}

Then in your TextBox keypress event, do this:

if (e.KeyCode == Keys.Enter) {
    e.SuppressKeyPress = true;
    Timer1.Enabled = true;
}

That seems to work...

You could try creating your own textbox and handle the keydown event like so:

public class MyTextBox : TextBox
{

    protected override void OnKeyDown(KeyEventArgs e)
    {
        switch (e.KeyCode)
        {          
            case (Keys.Return):
              /*
               * Your Code to handle the event
               * 
               */                   
                return;  //Not calling base method, to stop 'ding'
        }

        base.OnKeyDown(e);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM