C#MessageBox使密钥处理程序忽略SuppressKeyPress
考虑使用以下组件的Windows窗体应用程序C#MessageBox使密钥处理程序忽略SuppressKeyPress,c#,.net,winforms,C#,.net,Winforms,考虑使用以下组件的Windows窗体应用程序 partial class Form1 { private System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox(); private void InitializeComponent() { textBox.Multiline = true; Controls.Add(this.textBox);
partial class Form1
{
private System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox();
private void InitializeComponent()
{
textBox.Multiline = true;
Controls.Add(this.textBox);
KeyPreview = true;
KeyDown += new System.Windows.Forms.KeyEventHandler(Form1_KeyDown);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
if (textBox.Text.Length > 10)
MessageBox.Show("Test");
}
}
}
现在,预期的行为是将文本写入textBox
,然后按enter键。如果文本是
- 如果时间不够长,则不会发生任何事情(由于
),并且会发生这种情况e.SuppressKeyPress=true;
- 足够长时,应弹出空的
,并按消息框
不应到达键。Enter
组件。但是,当MessageBox弹出时,文本将包含由回车引起的换行符文本框
这是预期的行为还是错误,还是我是唯一遇到这种情况的人?您可以通过以下方式调用消息框来解决问题:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
this.BeginInvoke(new Action(() => {
if (textBox.Text.Length > 10)
MessageBox.Show("Test");
}));
}
}
MessageBox在错误的位置使用时是危险的,与臭名昭著的DoEvents()一样危险。它导致了再进入问题。它会使SuppressKeyPress请求出错,因为只有在事件处理程序完成后才能执行。直到消息框关闭后才会发生。由于MessageBox发送消息,它也会发送按键,因此SuppressKeyPress没有任何效果。修复方法很简单,请使用textBox.MaxLength=10。