C# KeyUp事件中MessageBox的回車(Enter)鍵回調問題解決方案
本文解析了C# KeyUp事件中MessageBox的回車(Enter)鍵出現(xiàn)回調問題的解決辦法。具體問題如下:
在一個窗體上有一個名為txtTest的Textbox控件,如果在此控件的KeyUp事件中有按回車鍵 彈出messagebox消息框,那么在彈出的messagebox中如果按回車鍵去執(zhí)行messagebox上的按鈕,再回車鍵還會在KeyUp事件中繼續(xù)執(zhí)行。一直按回車鍵的話將循環(huá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)回車鍵回調的問題。
相關文章
WinForm自定義函數(shù)FindControl實現(xiàn)按名稱查找控件
這篇文章主要介紹了WinForm自定義函數(shù)FindControl實現(xiàn)按名稱查找控件,需要的朋友可以參考下2014-08-08

