关闭子窗体后运行代码

本文关键字:运行 代码 窗体 | 更新日期: 2023-09-27 18:04:03

所以我有这个代码

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

所以在我点击更新后,它将运行子表单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

现在我的问题是,关闭子Form1后,它不运行MyForm_FormClosed,它应该启用菜单。Items[2] and updaterAccess()

我想我在mainForm中缺少了一些东西

关闭子窗体后运行代码

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

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

如果你想在VB中这样做:

AddHandler ShowProgress.FormClosed, AddressOf MyForm_FormClosed