-4

So I have Form1 and Form2.

When I close Form2 using this.Close(), I want Form1 to detect the close and execute a code.

Can this be done?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
SunAwtCanvas
  • 1,261
  • 1
  • 13
  • 38
  • JohnEphraimTugado I would not say it's a duplicate, because Denise probably doesn't know about DialogResult. However, Denise, the link from John is your answer. – Antoine Oct 04 '18 at 05:46
  • @Antoine Thanks :) I honestly didn't know about the DialogResult and yup :) I'll give it a look – SunAwtCanvas Oct 04 '18 at 05:51
  • @JohnEphraimTugado Thanks for sharing that :) So both the DialogResult and using FormClosing event methods fixed my problem!. I think I'll stick with the DialogResult just because I could do more with it :) – SunAwtCanvas Oct 04 '18 at 05:57
  • @Denise just a quick tip. Always hover your mouse over the method just to see what it returns. Most of the times it's not just void. This will help you in the future very often with problems. – slow Oct 04 '18 at 07:46
  • I feel like im being bullied o.o...How can u just say for certain I actually came across those other posts before? – SunAwtCanvas Oct 05 '18 at 08:52

1 Answers1

0

Yes you can execute whaever you want in FormClosing event, but you need to declare a static property on Form1 and set value on FormClosing in Form2 , write whatever you want to execute in the set{} method of peroperty.

// in Form 2
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
    Form1.IsForm2Closed = true;
}

// in Form 1
private static _isForm2Closed ;
public static bool IsForm2Closed 
{
    get
    {
        return _isForm2Closed;
    }
    set
    {
        _isForm2Closed = value;

       if(value)
       {
           // do whatever you want to execute here.
       }
    }
}
Siavash
  • 2,813
  • 4
  • 29
  • 42
  • 2
    If you're going as far as this, why not just subscribe to the `FormClosing` event of `Form2` from `Form1`? The problem you've got at the moment, is that if you want to alter any instance members or call any instance methods in `Form1`, you can't, because your code is using a static property. It also seems like a misuse of property setters. – ProgrammingLlama Oct 04 '18 at 05:47
  • this is a good idea, could you make an example of it, and put it here? – Siavash Oct 04 '18 at 05:49
  • 1
    @SiavashGhanbari So in form1 i'll just constantly execute a code to check that bool `IsForm2Closed`? – SunAwtCanvas Oct 04 '18 at 05:53
  • @Denise yes that is what I mean, this will be work, but I think John comment is considerable. – Siavash Oct 04 '18 at 05:56
  • 2
    @SiavashGhanbari Yup :) Actually both methods fixed my issue. thanks for helping me :) – SunAwtCanvas Oct 04 '18 at 05:58
  • @Denise What John means here is that you subscribe to the FormClosing event like in this answer but then from `Form1` when you make it (it being `Form2`) – EpicKip Oct 04 '18 at 07:44