我试图从另一个调用一个EventHandler方法。例如,我想链接Logout按钮和表单exit,所以我有这个代码:
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');
}
答案 0 :(得分:2)
试试这个:
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();
}
答案 1 :(得分:1)
处理事件并要求确认是不同的事情:
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事件。