简体   繁体   中英

An Event Handler when Close Button is clicked in windows form

I was wondering if there are any event handlers if the user clicked the close button in a windows form. My initial plan was when the user clicked the close button, it will return a boolean to the caller or whoever called that form. for example

public void newWindow(){

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

}

is that possible?

If you are using .ShowDialog(), you can obtain a result via the DialogResult property.

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

Then in your 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 do not want to open the 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
}

You should take a look at the FormClosing Event or since you are using ShowDialog you can do something like this. You can also change the DialogResult that is returned in the FormClosing Event.

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

You're almost there!

You don't need the if(nw.isClosed) , the line do something will only get executed when nw will be closed

If you need to 'return' a value from that dialog, know this: The dialog is not immediatly released when you close it. So you can do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM