我正在尝试从另一个方法调用一个EventHandler方法。例如,我想将"注销"按钮与表单出口链接起来,所以我有这样的代码:
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Bla, bla?", "Logout", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
我想从这个事件中称之为:
private void btnLogOut_Click(object sender, EventArgs e)
{
FormMain_FormClosing(null, 'not sure what goes here');
}
试试这个:
private void btnLogOut_Click(object sender, EventArgs e)
{
FormMain_FormClosing(null, null);
}
或
private void button1_Click(object sender, EventArgs e)
{
Form1_FormClosing(
null,
new FormClosingEventArgs(CloseReason.UserClosing, false));
}
即使我的答案涵盖了如何链接事件处理程序部分,这个特定的解决方案也会导致一个问题:表单无法关闭单击按钮
正确的解决方案是
private void button1_Click(object sender, EventArgs e)
{
Close();
}
处理事件和请求确认是分开的:
private static bool UserConfirmedToLogout()
{
return MessageBox.Show("Bla, bla?", "Logout", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK;
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = !UserConfirmedToLogout();
}
private void btnLogOut_Click(object sender, EventArgs e)
{
Close();
}
当调用Close()时,FormClosing事件也会被触发。