无法禁用文本框keydown事件上的蜂鸣声

时间:2013-10-07 07:56:43

标签: c# winforms

下面是我在文本框KeyDown()事件上按“Enter”时禁用哔声的代码:

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

但是当我在文本框中按“Enter”时,它会一直发出哔哔声。我做错了什么?

3 个答案:

答案 0 :(得分:3)

根据您的评论,显示MessageBox会干扰您对SuppressKeyPress属性的设置。

解决方法是在方法完成之后延迟MessageBox的显示:

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

答案 1 :(得分:2)

抱歉,我刚刚意识到你有一个MessageBox显示。

你可以做的是拥有Timer,然后点燃SaveData()方法。

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

然后在你的TextBox按键事件中,执行以下操作:

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

这似乎有用......

答案 2 :(得分:0)

您可以尝试创建自己的文本框并像这样处理keydown事件:

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);
    }
}
相关问题