Event handler when the close button is clicked in the window form

I was wondering if there are any event handlers if the user clicked the close button on the window form. My original plan was when the user clicked the close button, it will return a boolean to the caller or anyone who invoked this form. eg

public void newWindow(){

      NewForm nw = new NewForm();
      nw.ShowDialog();
      if(nw.isClosed){
       do something
   }

}

      

possibly?

+3


source to share


3 answers


If you use .ShowDialog (), you can get the result through the DialogResult property.

public void newWindow()
{
    Form1 nw = new Form1();
    DialogResult result = nw.ShowDialog();
    //do something after the dialog closed...
}

      

Then, in the click event handlers on Form1:



private void buttonOk_Click(object sender, EventArgs e)
{
     this.DialogResult = DialogResult.OK;
}

private void buttonCancel_Click(object sender, EventArgs e)
{
     this.DialogResult = DialogResult.Cancel;
}

      

If you don't want to open a new form as a dialog, you can do this:

public void newWindow()
{
    Form2 nw = new Form2();
    nw.FormClosed += nw_FormClosed;
    nw.Show();
}

void nw_FormClosed(object sender, FormClosedEventArgs e)
{
    var form = sender as Form2;

    form.FormClosed -= nw_FormClosed; //unhook the event handler

    //you can still retrieve the DialogResult if you want it...
    DialogResult result = form.DialogResult;
    //do something
}

      

+5


source


You should take a look at the FormClosing Event or as long as you are using ShowDialog

you can do something like this. You can also change DialogResult

which is returned in the event FormClosing

.



DialogResult dr = nw.ShowDialog();
if (dr == DialogResult.Cancel)
{
    //Do Stuff
}

      

+1


source


You're almost there!

You don't need it if(nw.isClosed)

, the line do something

will only be executed on closenw

If you need to "return" a value from this dialog, find out about this: The dialog will not be immediately released when you close it. So, you can do something like this:

NewForm nw = new NewForm();
nw.ShowDialog();
var x = nw.Property1

      

0


source







All Articles