0
votes

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?

3
Isn't it a sound produced by the operating system ?ffarquet
Yes Windows beep sound. How can I disable it?firefalcon
@Dhaval as you see from my code I am also setting Handled and SuppressKeyPress to true, but it's not working.firefalcon
@Shohin sorry it my mistakeDhaval
Maybe sound is made by something else? Can't think of what, perhaps another TextBox or the form.Sinatr

3 Answers

2
votes

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

5
votes

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()));
  }
}
0
votes

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);
    }
}