C# 在 Windows 窗体中单击关闭按钮时的事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9866207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 10:59:40  来源:igfitidea点击:

An Event Handler when Close Button is clicked in windows form

c#.netwinformsevent-handling

提问by user962206

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

我想知道如果用户单击 Windows 窗体中的关闭按钮是否有任何事件处理程序。我最初的计划是当用户单击关闭按钮时,它将向调用者或调用该表单的任何人返回一个布尔值。例如

public void newWindow(){

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

}

is that possible?

那可能吗?

采纳答案by Eric Dahlvang

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

如果您使用 .ShowDialog(),您可以通过 DialogResult 属性获取结果。

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:

然后在 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
}

回答by Mathieu

You're almost there!

您快到了!

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

您不需要if(nw.isClosed),该行do something只会nw在关闭时执行

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

回答by Mark Hall

You should take a look at the FormClosingEvent or since you are using ShowDialogyou can do something like this. You can also change the DialogResultthat is returned in the FormClosingEvent.

你应该看看FormClosing事件,或者因为你正在使用ShowDialog你可以做这样的事情。您还可以更改事件中DialogResult返回的FormClosing

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