0

I am writing a program that navigates through a website containing a number of frames. I am using WinForms webBrowser control.

I had the same program written in visual basic script, where I have used the following code as a subprocedure to make sure that everything is loaded before trying to invoke click events etc.

Sub CheckIfLoaded
    Do while appIE.Busy = True OR appIE.ReadyState <> 4 : Wscript.Sleep(100) : Loop
End Sub

I am looking for something similar in C#. I don't think that WebBrowswer.DocumentCompleted event is the solution here, because as far as I understand the usage of it, I would have to put whole code into one webBrowser1_DocumentCompleted method in a large number of if statements, which seems really wrong.

The pseudo code would be:

private void DoOneSpecificThing (string[] ListOfThings)
{
    foreach (string ID in ListOfThings)
    {
      open webbrowser and navigate to page;
       CheckIfLoaded();
      Log In and load the first page;
       CheckIfLoaded();
      Tick a bunch of tickboxes, write in textboxes etc;
      Submit;
       CheckIfLoaded();
      Go to the next page;
       CheckIfLoaded();
      And do more stuff;
      Submit;
    }
}

There are a lot of procedures like that in my code (e.g. for logging in, for navigating to selected page, for filling forms, for setting options, for generating reports), so I would like to have one simple thing that would make sure that the page is loaded before trying to access its element, as I had in vbs.

I tried the following two solutions: (in the first one, the application never gets to load a page)

        int counter = 0;
        while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
        {
            counter += 1;
        }

(in the second, the application doesn't actually wait for the page to load, so I tend to get null reference errors and this kind of stuff InvalidArgument=Value of 'nav' is not valid for 'windowId'.)

        while (webBrowser.ReadyState != WebBrowserReadyState.Complete)
        {
            Application.DoEvents();
        }

Help will be greatly appreciated! Thanks in advance

Bartosz

Bartosz
  • 4,406
  • 7
  • 41
  • 80
  • A browser is (hopefully) multithreaded. Using events (when they are available) is much better than doing while+sleep+doevents loops. But yes, it can be more difficult to grasp from a developer perspective. you should start learning async programming. – Simon Mourier Feb 18 '14 at 10:54
  • I have just started learning programming, so this may be a bit too complicated for now. So you don't see any way to make sure that the browser has loaded everything? – Bartosz Feb 18 '14 at 15:49
  • Possible duplicate of [DocumentComplete event in Embedded IWebBrowser2 using write() method](https://stackoverflow.com/questions/20286451/documentcomplete-event-in-embedded-iwebbrowser2-using-write-method) – Paul Sweatte Jun 07 '17 at 00:42

0 Answers0