2

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 object". 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?

alcohol is evil
  • 686
  • 12
  • 34
  • Do you have any timers or asynchronous methods running in the background that could be effecting this? Do you have any events on the webBrowser1 object that would be called, say OnReadyStateChanged? – mellamokb Jul 22 '11 at 19:33

2 Answers2

7

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.

Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
  • 3
    Yeah, and that processing could cause reentrancy problems, `StackOverflowException` (in case DoEvents will call method that calls DoEvents again) and other funny kinds of stuff. It is better to be sure you're understand how `DoEvents` works before calling it. – Ivan Danilov Jul 22 '11 at 19:37
  • Absolutely. I think confusion about this method partly comes from the fact that once popular Visual Basic 6 had a method with exactly the same name which was used as a poor replacement to multi-threading. – Dan Abramov Jul 22 '11 at 19:43
  • Well, I didn't write in VB6, but it is still used as a replacement. With same results actually :) – Ivan Danilov Jul 22 '11 at 19:45
  • Slightly offtopic, but anyway. There's similar thing in low-level native programming on Windows called 'user APC' or asynchronous procedure call. Sometimes useful, but also very dangerous. – Ivan Danilov Jul 22 '11 at 19:47
2

DoEvents() is a bad solution here. You should use explicit thread or BackgroundWorker to load pages and leave UI thread to handle other stuff.

Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66
  • WebBrowser cannot run on a MTU adn BackgroundWorker creates MTU threads only – Odys Jan 12 '12 at 14:25
  • @odyodyodys did you mean MTA - Multiple Thread Apartment? In that case it is a bad idea to use this component like that. Maybe it allows to set content explicitly (instead of setting an Uri) or somehow to make content download asynchronous? – Ivan Danilov Jan 12 '12 at 14:52