本文解析了C# KeyUp事件中MessageBox的回車(Enter)鍵出現(xiàn)回調(diào)問題的解決辦法。具體問題如下:
在一個窗體上有一個名為txtTest的Textbox控件,如果在此控件的KeyUp事件中有按回車鍵 彈出messagebox消息框,那么在彈出的messagebox中如果按回車鍵去執(zhí)行messagebox上的按鈕,再回車鍵還會在KeyUp事件中繼續(xù)執(zhí)行。一直按回車鍵的話將循環(huán)進(jìn)行。
代碼如下所示:
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;}}}
為了避免這種情況出現(xiàn),可以把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里將不會再出現(xiàn)回車鍵回調(diào)的問題。
新聞熱點
疑難解答
圖片精選