r/visualbasic • • Dec 29 '20

VB.NET Help Can a Handler with a dynamic Sub remove itself?

[I can achieve the goal otherwise. This is a "is this possible" question.]

AddHandler allows a Sub to be specified dynamically:

    Dim Browser As New WebBrowser With {.Url = New Uri("http://google.com")}
    Controls.Add(Browser)

    AddHandler Browser.DocumentCompleted, Sub()
                                            Browser.Document.Forms.Item(0).InvokeMember("submit")
                                          End Sub

The problem with the above code, is that it keeps loading and running the handler. To fix the problem, the handler needs to remove itself.

If the handler were not dynamic, AddressOf could be used in both the AddHandler and RemoveHandler statements. Is there way for a dynamic handler to remove itself?

6 Upvotes

3 comments sorted by

5

u/chacham2 Dec 29 '20

Took me a minute to search with "lambda," which brought me to this article.

So, to answer my own question:

Dim Document_Completed As WebBrowserDocumentCompletedEventHandler = Sub()
                                                                     Browser.Document.Forms.Item(0).InvokeMember("submit")
                                                                     RemoveHandler Browser.DocumentCompleted, Document_Completed
                                                                    End Sub

3

u/laancelot Dec 30 '20

Hey props for answering your question, too few people will do this. Some day, a dev will look for this information and high five you through time and space.

2

u/chacham2 Jan 18 '21

Fwiw, i just came back myself to check one detail, and smiled at your comment again. :)