Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#MessageBox使密钥处理程序忽略SuppressKeyPress_C#_.net_Winforms - Fatal编程技术网

C#MessageBox使密钥处理程序忽略SuppressKeyPress

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);

考虑使用以下组件的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
,然后按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。