C# KeyUp事件中MessageBox的回车(Enter)键问题

假如一个窗体上有一个名为txtTest的Textbox控件,

如果在此控件的KeyUp事件中有按回车键 弹出messagebox消息框,

那么在弹出的messagebox中如果按回车键去执行messagebox上的按钮,

那么回车键还会在KeyUp事件中继续执行。一直按回车键的话将循环进行。

如下:

 private void txtTest_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (MessageBox.Show("输入完了?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    this.lblTest.Text = this.txtTest.Text;
                }

            }
        }


为了避免这种情况出现,可以把KeyUp里的程序移到KeyDown事件中即可

private void txtTest_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (MessageBox.Show("输入完了?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    this.lblTest.Text = this.txtTest.Text;
                }

            }
        }

在KeyDown里将不会出现回车键回调的问题。


猜你喜欢

转载自blog.csdn.net/mao_mao37/article/details/73332280