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
,当我在 MessageBoxENTER/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;
}
}