当窗体重新成为焦点时,Windows窗体事件

时间:2018-09-18 12:00:04

标签: c# winforms

我有2种形式:Form1和Form2

Form1具有启动Form2的按钮。 Form2显示为弹出窗口,Form1仍显示在背景中。 通过按X关闭Form2时,我需要对Form1进行一些操作(例如刷新它获得的数据,因为在Form2上进行的输入可能会影响它)。

我尝试过在Form1上激活,显示,输入,GotFocus,VisibleChanged之类的事件,以查看是否在Form1恢复活力时触发了其中的任何事件,但它们没有帮助。

请问如何才能做到这一点? 关闭Form2后,Form1重新聚焦时会触发什么事件。

3 个答案:

答案 0 :(得分:3)

如果Form1具有Form2的实例,那么您可以在Form1中处理Form2的FormClosing事件:

public Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        CreateForm2();
    }

    public void CreateForm2()
    {
        Form2 form2 = new Form2();
        form2.FormClosing += form2_FormClosing;
    }

    public void form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        // This bit removes the event handler so clears up memory leaks
        Form2 form2 = sender as Form2;
        if (form2 != null)
        {
            form2.FormClosing -= form2_FormClosing;
        }

        // Do stuff here when form2 is closed
    }
}

答案 1 :(得分:1)

尝试一下

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();

        f2.Closed += F2_Closed;
    }

    private void F2_Closed(object sender, EventArgs e)
    {
        MessageBox.Show("Form2 was closed");
    }

答案 2 :(得分:0)

也许尝试使用ShowDialog()

Form2中:

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            // use whichever DialogResult is applicable - the option to cancel might be nice.
            this.DialogResult = DialogResult.OK;
        }

Form1中:

Form2 frmPopup = new Form2();
            if (frmPopup.ShowDialog() == DialogResult.OK)
            {
                // do whatever needs to happen when Form2 closes
            }