处理动态(运行时)控件的事件 - VB.NET
我有一个在运行时创建并添加到窗体中的 WebBrowser 控件。
如何将此控件连接到可以在运行时处理其事件的子例程?
I have a WebBrowser control that is created and added to the form during run-time.
How do I connect this control to subroutine that can handle its events at run-time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
示例
AddHandler SharedTimer.Tick、AddressOf SharedTimer_Tick
Example
AddHandler SharedTimer.Tick, AddressOf SharedTimer_Tick
'我有一种方法可以发现控件并在某些情况下添加处理程序。
'这是一个简化的示例。
'是否可以在运行时传入处理程序?
“我想做一些更像这样的事情......
我遇到的问题是调用该方法。 这不起作用:
'I have a method that discovers controls and adds handlers in certain situations.
'Here is a simplified example.
'Is it possible to pass in the handler at run time?
'I'm looking to do something more like this...
The problem I'm having is in calling the method. This does not work:
您可以使用 Addhandler 语句来执行这些操作。
您可以在运行时将任何事件处理程序添加到网络浏览器,如下所示
,类似地,您可以使用RemoveHandler,它会断开事件与事件处理程序的连接,如下所示:
You can use the Addhandler statement for doing these things.
You can add any event handlers at run time to the webbrowser like this
and similarly you can use RemoveHandler, which disconnects an event from an event handler like this:
请使用 AddHandler
例如
,当您想摆脱时, 根据
在您的情况下,您可能会
假设您创建了一个名为 HandleDocumentCompleted 的事件处理程序,
您的需要,您还可以使用 WithEvents 关键字,当您声明您的网络浏览器时; 请参阅文档。
Use AddHandler
e.g.
and when you want to get rid of it (and you should get rid of it when you're done using it)
in your case, you might have something like
assuming you'd created an event handler called HandleDocumentCompleted
Depending on your needs, you could also use the WithEvents keyword when you declare your webbrowser; see the documentation.
使用
AddHandler
的替代方法是 VB 中的声明性事件语法。 要使用它,您需要使用WithEvents
关键字声明该控件(作为私有成员)。 然后,可以在方法上使用Handles
关键字来处理相应的事件:这种方法主要有两个优点:
RemoveHandler
,An alternative to using
AddHandler
is the declarative events syntax in VB. To use it, you declare the control (as a private member), using theWithEvents
keyword. Then, theHandles
keyword can be used on methods to handle the appropriate events:There are mainly two advantages to this method:
RemoveHandler
,我通过检查表单设计器生成的代码了解到了这一点。 从那里复制一个示例,如果您环顾四周,您可能会学到一些有关在运行时设置控件的其他有价值的东西。
在 C# 中,它是通过 += 完成的,在以函数作为参数的类的事件成员上,但我没有方便地检查自己的 VB.net...抱歉。
编辑:它是 AddHandler 正如 Daniel L 在他的回答中所描述的那样,详细信息请参见 msdn。
I learned about this from examining the Form Designer generated code. Copy one of the examples from there, and if you look around you might learn some other valuable things about setting up controls at run-time.
In C# its done with +=, on an event member of a class with a function as the parameter, but I do not have VB.net handy to check myself... sorry.
EDIT: It's AddHandler as described well by Daniel L in his answer, and in full detail at msdn.