Problem with Application.DoEvents() while waiting for WebBrowser to finish loading
I'm trying to load WebBrowser content and after that I want to add some text and scroll to the bottom.
Here's example of my code:
webBrowser1.Url = new System.Uri("file:///" + filePath);
webBrowser1.Document.Body.InnerHtml += text;
webBrowser1.Document.Body.ScrollTop = webBrowser1.Document.Body.ScrollRectangle.Height;
When I run it, there's an unhandled exception "Object reference not set to an instance of an obj开发者_开发知识库ect". Or when I comment line that does the scrolling, then text is added to previous content of the WebBrowser and then navigating to new content.
So after 1st line of my example code I put:
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
but it messes up everything. My application is doing really strange things, for example calling the same method many times, when it should be called once.
Is there any solution?
I think you actually want to subscribe to DocumentCompleted
event.
Application.DoEvents
only processes pending Windows message loop items.
In either case, make sure you understand possible drawbacks of calling DoEvents
before using it at all.
DoEvents()
is a bad solution here. You should use explicit thread or BackgroundWorker
to load pages and leave UI thread to handle other stuff.
精彩评论