如何处理VB.NET中以编程方式创建的窗体的关闭事件? [英] How to handle on close event of a programmatically created Form in VB.NET?
问题描述
我是VB.NET的新手,但我坚持以下几点:
I am new to VB.NET and I'm stuck with the following:
我想在以编程方式创建的窗体关闭之前执行一些操作.
I want to perform some operations before a programmatically-created Form closes.
我需要处理我的Form(用代码创建)的Close事件.
I need to handle the Close event of my Form (created in code).
我该怎么做?
下面是他们使用C#的方式
Below is how they do it with C#
{
Form1 f = new Form1();
f.FormClosed += new FormClosedEventHandler(f_FormClosed);
f.Show();
}
void f_FormClosed(object sender, FormClosedEventArgs e)
{
// Do stuff here
}
推荐答案
在VB.NET中,事件的处理方式有所不同.如果除了表单的 FormClosed
委托声明之外,还想使用 Handles
子句,则需要声明对象(本例中为 Form
)在模块级别上使用 WithEvents
关键字:
In VB.NET events are handled a little bit differently.
If you want to use the Handles
clause in addition to the form's FormClosed
delegate declaration, you need to declare the object (Form
in your case) with the WithEvents
key word at a module level:
Private WithEvents frmX AS New Form
然后您可以编写:
Private Sub frmX_FormClosed(sender As Object, e As FormClosedEventArgs) Handles frmX.FormClosed
End Sub
然后,编译器将负责适当地附加和分离处理程序.
The compiler will then take care of attaching and detaching the handler as appropriate.
如果您想控制自己,请在任意位置声明 Form
,并根据需要使用 AddHandler
和 RemoveHandler
指令:
If you want to take control yourself, then declare the Form
wherever you'd like and use the AddHandler
and RemoveHandler
directives as appropriate:
// Define the handler delegate as usual:
Private Sub frmX_FormClosed(sender As Object, e As FormClosedEventArgs)
End Sub
// Somewhere else in your code use this:
// To attach the handler:
AddHandler frmX.FormClosed, AddressOf Form5_FormClosed
// To detach the handler:
RemoveHandler frmX.FormClosed, AddressOf frmX_FormClosed
.FormClosed
将在 AddHandler
/ RemoveHandler
上下文中弹出.请注意 AddressOf
关键字.当您需要指定委托时,这是强制性的.
The .FormClosed
will popup in the AddHandler
/ RemoveHandler
context.
Note the AddressOf
keyword. It is mandatory when you need to specify a delegate.
这篇关于如何处理VB.NET中以编程方式创建的窗体的关闭事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!