本文解析了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里將不會再出現回車鍵回調的問題。
新聞熱點
疑難解答