[英]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. 如果您使用.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
}
You should take a look at the FormClosing Event or since you are using ShowDialog
you can do something like this. 您应该看看FormClosing事件,或者因为您使用ShowDialog
您可以执行类似的操作。 You can also change the DialogResult
that is returned in the FormClosing
Event. 您还可以更改FormClosing
事件中返回的DialogResult
。
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(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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.