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?
AddHandler Obj.Ev_Event, AddressOf EventHandler
and when you want to get rid of it (and you should get rid of it when you're done using it)
RemoveHandler Obj.Ev_Event, AddressOf EventHandler
in your case, you might have something like
Dim web as New WebBrowser() AddHandler web.DocumentCompleted, AddressOf HandleDocumentCompleted
assuming you'd created an event handler called HandleDocumentCompleted
An alternative to using
AddHandler is the declarative events syntax in VB. To use it, you declare the control (as a private member), using the
WithEvents keyword. Then, the
Handles keyword can be used on methods to handle the appropriate events:
Private WithEvents m_WebBrowser As WebBrowser Private Sub WebBrowser_Navigate(ByVal sender As Object, ByVal e As WebBrowserNavigatedEventArgs) Handles m_WebBrowser.Navigate MsgBox("Hi there") End Sub Private Sub SomeActionThatCreatesTheControl() m_WebBrowser = New WebBrowser() End Sub
There are mainly two advantages to this method: