0

我试图从另一个调用一个 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');
}
4

2 回答 2

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();
}
于 2012-08-20T20:21:12.160 回答
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 事件。

于 2012-08-20T20:34:50.417 回答