Proper way to assign a event handler to HtmlDocument.MouseDown in C#?
Since you can only assign it after the doc开发者_Python百科ument have been loaded, and you don't need to assign it every time a document loads, do I just don't have other choice than to do something like this?
private void WebBrowser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
if (!mouseDownAssigned) // mouseDownAssigned is a bool with start value false
{
mouseDownAssigned = true;
this.Document.MouseDown +=
new HtmlElementEventHandler(Document_MouseDown);
}
}
Which is kinda ugly and not elegant. Got a feeling this is not what Microsoft had in mind.
I don't believe it is what MS had in mind either. If I had to guess, it comes from the fact that there is some sort of proxy between the document and the web browser which does the event handling which only gets initialized when the first document is loaded, instead of when the control is loaded.
I think this is the closest to an elegant solution:
public MyWebBrowser()
{
InitializeComponent();
this.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(SuperWebBrowser_DocumentCompleted);
this.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(SuperWebBrowser_DocumentFirstCompleted);
}
private void SuperWebBrowser_DocumentFirstCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(SuperWebBrowser_DocumentFirstCompleted);
this.Document.MouseDown += new HtmlElementEventHandler(Document_MouseDown);
}
private void SuperWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
That way I don't need to check a variable every time a document completes. Guess that's kinda what Microsoft had in mind.
精彩评论