考虑具有以下组件的 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);
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
并按回车键。如果文本是
- 时间不够长,什么都不会发生(由于
e.SuppressKeyPress = true;
)并且这种情况发生了。
- 足够长,空
MessageBox
应该弹出并且Keys.Enter
不应达到textBox
成分。但是,当弹出MessageBox时,文本中会包含回车导致的换行符。
这是故意的行为,还是错误,还是我是唯一经历过这种情况的人?
您可以通过调用消息框来解决问题BeginInvoke
这边走:
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");
}));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)