0

Good day to all. I have a question, i'm using wpf and i cant find the right way of closing the form1 from form2.

WpfForm form1 = new WpfForm();
form1.close();

Please i need help.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sephiroth111
  • 127
  • 1
  • 5
  • 14
  • 2
    what have you tried already? If you don't want to tight-couple the forms (not a good idea) you might want some kind of message-passing but those stuff depends on the system you are building and with only this few lines of code we cannot guess on what you want to really do. – Random Dev Mar 05 '12 at 16:40
  • 2
    WPF uses the [Window class](http://msdn.microsoft.com/en-us/library/system.windows.window.aspx) and does have the [close](http://msdn.microsoft.com/en-us/library/system.windows.window.close.aspx) method, are you show your `WpfForm` derives from window? What then is the problem you face? – gideon Mar 05 '12 at 16:42

3 Answers3

2

As Matt has stated you need to have a reference in your first form of you second form, so assuming that you will have that reference you can simply add an event handler like the one shown below at some point in your first form's code when the reference to the second form is set to an instance, something like your Window_Loaded event would be a good candidate.

secondWindow.Closing += (s, e) => this.Close();

The above is an inline event handler, if you'd rather have more verbose code you could do something like:

secondWindow.Closing += CloseMe;

private void CloseMe(Object sender, EventArgs e)
{
    this.Close();
}

Incase you're interested, Mr. Skeet discusses inline event handler caveats in another question here.

Community
  • 1
  • 1
Paulie Waulie
  • 1,690
  • 13
  • 23
1

You need a reference to your first form in your second. Then you can simply call close using that reference.

There are a few ways to handle it. You could add a property to your second form to hold a reference to your first form. When you create your second form, you will set that property and then in whatever the event in your second form is supposed to close the first form (e.g. clicking a button), you can use that reference to close the form.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
1

As said Matt and Paulie you need have a reference in your first form, so if you would like do this without a reference you can use the static access modifier and delegates like here;

    public delegate void Method();
    private static Method close;

    public Form1()
    {
        InitializeComponent();
        close = new Method(Close);
    }

    public static void CloseForm()
    {
        close.Invoke();
    }

Next in your second form you can close the first one without references writing simply this:

Form1.CloseForm();
Omar
  • 16,329
  • 10
  • 48
  • 66