C#MessageBox导致按键处理程序忽略SurpressKeyPress [英] C# MessageBox casues key handler to ignore SurpressKeyPress

查看:65
本文介绍了C#MessageBox导致按键处理程序忽略SurpressKeyPress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑具有以下组件的Windows Forms应用程序

Consider Windows Forms application with following components

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.如果文字是

Now, expected behaviour, is to write text to textBox and press enter. If the text is

  • 时间不够长,什么也不会发生(由于 e.SuppressKeyPress = true; )而发生.
  • 足够长,应该弹出空的 MessageBox Keys.Enter不能到达 textBox 组件.但是,当MessageBox弹出时,文本将包含回车引起的换行符.
  • not long enough, nothing should happen (due to e.SuppressKeyPress = true;) and that happens.
  • is long enough, empty MessageBox should pop up and Keys.Enter should not reach the textBox component. However, when MessageBox pops up, the text will contain line-break caused by the enter.

这是预期的行为还是bug,或者我是唯一遇到这种情况的人?

Is this intended behaviour, or bug, or am I the only on experiencing this?

推荐答案

您可以通过以下方式使用 BeginInvoke 调用消息框来解决问题:

You can solve the problem by calling the message box using BeginInvoke this way:

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

这篇关于C#MessageBox导致按键处理程序忽略SurpressKeyPress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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