简体   繁体   English

通过传递参数从另一个事件方法中调用一个事件方法

[英]Calling one event method from another event method with passing a parameter

I am trying to call one EventHandler method from another. 我试图从另一个调用一个EventHandler方法。 For example, I would like to link Logout button with form exit, so I have this code: 例如,我想将“退出”按钮与表单退出链接,因此我有以下代码:

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;
    }
}

and I want to call it from this event: 我想从这个事件中调用它:

private void btnLogOut_Click(object sender, EventArgs e)
{            
    FormMain_FormClosing(null, 'not sure what goes here');
}

Try this: 尝试这个:

private void btnLogOut_Click(object sender, EventArgs e)
{            
    FormMain_FormClosing(null, null);
}

or 要么

private void button1_Click(object sender, EventArgs e)
{
    Form1_FormClosing(
        null, 
        new FormClosingEventArgs(CloseReason.UserClosing, false));
}

Even if my answer cover how to link event handlers part, this particular solution leads you to a problem: form won't close clicking button. 即使我的回答涵盖了如何链接事件处理程序部分,该特定解决方案也会导致您遇到问题:表单不会关闭单击按钮。
Correct solution is 正确的解决方案是

private void button1_Click(object sender, EventArgs e)
{
    Close();
}

Handling the event and asking for confirmation are seperate things: 处理事件并要求确认是分开的事情:

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();
}

When Close() is called, the FormClosing event is fired too. 调用Close()时,也会触发FormClosing事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM