要在按下ESC时关闭表单,我一直使用:
protected override bool ProcessDialogKey(Keys keyData) //Exit form if Esc is pressed
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e) //Ask for confirmation when "X" is clicked
{
//Define a messagebox
const string message = "Are you sure that you want to exit the application?";
const string caption = "Close Application";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
//Cancel the action if NO is clicked
e.Cancel = (result == DialogResult.No);
}
今天,我意识到可以使用以下代码实现相同的目的:
private void frmMain_KeyUp(object sender, KeyEventArgs e)
{
//Close form when ESC key is pressed
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
private void frmMain_FormClosing(object sender, FormClosingEventArgs e) //Ask for confirmation when "X" is clicked
{
//Define a messagebox
const string message = "Are you sure that you want to exit the application?";
const string caption = "Close Application";
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
//Cancel the action if NO is clicked
e.Cancel = (result == DialogResult.No);
}
因此,我想知道遵循第一组代码是否有任何优势,因为第二组代码似乎更轻松。
慕莱坞森
Helenr
相关分类