Sri
Sri

Reputation: 155

Windows forms event when the form comes back on focus

I have 2 forms: Form1 and Form2

Form1 has got a button to launch Form2. Form2 appears as a pop up with Form1 still shown in the background. When Form2 is closed by pressing X i need some action to occur on Form1 (like refreshing the data it has got because the input made on Form2 might have impacted it).

I have tried events like Activated, Shown, Enter, GotFocus, VisibleChanged on Form1 to see if any of these get triggered when Form1 comes back to life but they did not help.

How can this be achieved this please? What event is triggered when Form1 comes back to focus after Form2 is closed.

Upvotes: 0

Views: 1399

Answers (3)

FvL
FvL

Reputation: 36

Perhaps try using ShowDialog():

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

In Form1:

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

Upvotes: 0

Baral
Baral

Reputation: 3141

Give this a try

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

Upvotes: 1

Handbag Crab
Handbag Crab

Reputation: 1538

If Form1 has an instance of Form2 then you can handle the FormClosing event of Form2 in Form1:

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

Upvotes: 3

Related Questions