在子窗体关闭后运行代码

时间:2014-05-20 02:25:15

标签: c#

所以我有这段代码

public void Update_Click(object sender, EventArgs e)
{
    using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
    {
        menu.Items[2].Enabled = false;
        ShowProgress.ShowDialog();
        ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
    }
}

public void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
    updaterAccess();
    menu.Items[2].Enabled = true;
}

所以在我点击Update后,它将运行子表单Form1 这就是:

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    notifyIcon1.Visible = true;
    notifyIcon1.BalloonTipTitle = "Update Complete";
    notifyIcon1.BalloonTipText = "Successfully Update";
    notifyIcon1.ShowBalloonTip(500);
    timer1.Interval = 4000;
    timer1.Enabled = true;
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Start(); 
}

private void timer1_Tick(object sender, EventArgs e)
{
    notifyIcon1.Dispose();
    this.Close();
}

因此您可以看到它在具有计时器的后台工作程序上运行以关闭子Form1

现在我的问题是,在关闭Child Form1后,它不会运行MyForm_FormClosed,它应该再次启用menu.Items [2]并且updaterAccess()

我想我在mainForm中遗漏了一些东西

3 个答案:

答案 0 :(得分:5)

在触发ShowDialog

之前附加事件处理程序
public void Update_Click(object sender, EventArgs e)
    {
        using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
        {
            menu.Items[2].Enabled = false;
            ShowProgress.FormClosed += new FormClosedEventHandler(MyForm_FormClosed); //Attached the event handler before firing ShowDialog
            ShowProgress.ShowDialog();
        }
    }

答案 1 :(得分:3)

ShowDialog同步显示模式对话框,这意味着它会一直阻塞,直到表单关闭(以下代码在表单关闭之前不会运行)。因此,当ShowDialog返回表单时已经关闭

你可以在@Jade建议调用ShowDialog()之前附加事件处理程序,这将起作用,但老实说你根本不需要使用事件系统。只需等待ShowDialog返回,然后执行表单关闭时的操作:

public void Update_Click(object sender, EventArgs e)
{
    using (PccBiometricsHandler.Form1 ShowProgress = new PccBiometricsHandler.Form1())
    {
        menu.Items[2].Enabled = false;
        ShowProgress.ShowDialog();
    }

    updaterAccess();
    menu.Items[2].Enabled = true;
}

答案 2 :(得分:0)

如果你想在VB中这样做:

AddHandler ShowProgress.FormClosed, AddressOf MyForm_FormClosed