1

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
firefalcon
  • 500
  • 2
  • 8
  • 21

3 Answers3

6

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()));
  }
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
2

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...

user959631
  • 1,004
  • 2
  • 14
  • 34
  • Instead of using Timer, the more elegant solution is using this.BeginInvoke() to delay the MessageBox and prevent beeping. See LarsTech answer below. – Maris B. Mar 10 '21 at 11:52
  • @MarisB. Apologies, this answer was made a long time ago when I was just starting out. I agree that the answer below is a better approach. I can update my answer. – user959631 Mar 10 '21 at 11:59
0

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);
    }
}
TDull
  • 753
  • 5
  • 12