Yohanes Nurcahyo
Yohanes Nurcahyo

Reputation: 621

Why WinForm Form.FormClosed Event Is Not Triggered From a Form Holder?

I have 2 Forms, FormA and FormB. FormA is opened from FormB button clicked event. And in FormA holder, FormClosed event from FormA is registered. The problem is if I close FormB, the FormA is closed as well but the FormClosed event is not called.

How to make FormClosed event is called?
I want FormA Holder is notified when FormA is closed/closing to dispose the resources.

This is the simplified code snippet:

internal class FormA : Form
{
    public FormA()
    {
        this.Text = @"Form A";
    }
}

internal class FormAHolder
{
    internal FormA FormA { get; private set; }

    internal FormAHolder()
    {
        this.FormA = new FormA();
        this.FormA.FormClosed += this.OnFormAFormClosed;
    }

    private void OnFormAFormClosed(object sender, FormClosingEventArgs e)
    {
        Console.WriteLine("Hallo, please call me!!!");
        //// Clean up code should be here....
    }
}

internal class FormB : Form
{
    public FormB()
    {
        this.Text = @"Form B";
        var button = new Button { Text = @"Open Form A" };
        button.Click += this.OnButtonClick;
        this.Controls.Add(button);
    }

    private void OnButtonClick(object sender, EventArgs e)
    {
        var formAHolder = new FormAHolder();
        formAHolder.FormA.Show();
    }
}

[Test]
public void FormTest()
{
    var formB = new FormB();
    formB.ShowDialog();
}

Upvotes: 2

Views: 996

Answers (2)

Jens Kloster
Jens Kloster

Reputation: 11277

You need to start FormB with a message loop.
use this:

 Application.Run(new FormB());

instead of

var formB = new FormB();
formB.ShowDialog();

Application.Run does exacly that, but you can only call it once pr. Thread.

Upvotes: 1

kdh
kdh

Reputation: 937

You can try calling the cleanup code from the FormB Closed event, by extracting the cleanup code to a method in class FormAHolder and calling it when you need to.

Upvotes: 0

Related Questions