C# - 在 MessageBox 中按 Enter 触发控件 KeyUp 事件 [英] C# - Pushing Enter in MessageBox triggers control KeyUp Event

查看:41
本文介绍了C# - 在 MessageBox 中按 Enter 触发控件 KeyUp 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

系统:Windows7 Pro、Visual Studio 2010、C#

System: Windows7 Pro, Visual Studio 2010, C#

我有一个文本框:textBox1我设置了它的事件:

I have a textbox: textBox1 I set its event:

textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        button1.PerformClick();
    }
}

private void button1_Click(object sender, EventArgs e)
{ 
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        MessageBox.Show("Invalid data", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    } 
}

它工作正常,问题是,当输入的数据无效时,显示 MessageBox,当我在 MessageBox<上点击 ENTER/code> OK 按钮,它还会触发 textBox1_KeyUp,这会导致 MessageBox 再次出现.因此,它会触发 MessageBox OK 按钮,使其消失,并触发 textbox_keyUp ,然后再次显示消息框.

It works fine, the problem is, when the data entered is invalid, and thus the MessageBox is shown, when i hit ENTER on the MessageBox OK Button, it also triggers the textBox1_KeyUp, which causes the MessageBox to show up again. So, it triggers the MessageBox OK button, which causes it to disappear, and also triggers the textbox_keyUp which then causes the messagebox to show up again.

感谢您的帮助.

推荐答案

是的,消息框响应 key down 事件.你的 TextBox 也应该如此.改用 KeyDown 事件,问题解决了.也解决了用户平时听到的烦人的BEEP.

Yes, the message box responds to the key down event. So should your TextBox. Use the KeyDown event instead, problem solved. Also solves the annoying BEEP the user normally hears.

    private void textBox1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyData == Keys.Enter) {
            button1.PerformClick();
            e.SuppressKeyPress = true;
        }
    }

这篇关于C# - 在 MessageBox 中按 Enter 触发控件 KeyUp 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆