0

I simulate a login with a WebBrowser-Control and after that I read data from the page from the HTNML Source.

If I do it with 2 Buttons and 2 single clicks, it works perfectly:

private void btnTest_Click(object sender, EventArgs e)
{
   Login();
}

private void btnTest2_Click(object sender, EventArgs e)
{
   ReadData();
}

private static void Login()
{
   browser.Navigate("www.site.de");
   while (browser.ReadyState != WebBrowserReadyState.Complete)
   {
      Application.DoEvents();
      richLog.Text += "Warten...";
      Thread.Sleep(1000);
   }
   browser.Document.GetElementById("login_username").SetAttribute("value", username);
   browser.Document.GetElementById("login_password").SetAttribute("value", password);
   browser.Document.GetElementById("login_submit_6b86b171").InvokeMember("click");

   while (browser.ReadyState != WebBrowserReadyState.Complete)
   {
      Application.DoEvents();
      richLog.Text += Environment.NewLine + "Warten...";
      Thread.Sleep(10000);
   }
}

private static void ReadData()
{
   browser.Navigate("www.site.de/data");
   while (browser.ReadyState != WebBrowserReadyState.Complete)
   {
      Application.DoEvents();
      richLog.Text += Environment.NewLine + "Warten...";
      Thread.Sleep(1000);
   }
   richText.Text = browser.DocumentText;
   richLog.Text += Environment.NewLine + "Posts ausgelesen - Seite " + site;
}

If I do it with one button, it fails. The Site which is opened is the site in a NOT LOGGED-Status. I try to add a Thread.Sleep() with 10 Seconds or longer, but the response is the same.

private void btnTest_Click(object sender, EventArgs e)
{
   Login();
   ReadData();
}

Whats the difference? How to solve?

Brian
  • 5,069
  • 7
  • 37
  • 47
PassionateDeveloper
  • 14,558
  • 34
  • 107
  • 176

1 Answers1

1

Most likely, the problem is with this fragment:

   while (browser.ReadyState != WebBrowserReadyState.Complete)
   {
      Application.DoEvents();
      richLog.Text += Environment.NewLine + "Warten...";
      Thread.Sleep(10000);
   }

You call Application.DoEvents (which is an evil on its own) just once, then you block the UI thread's message pump with Thread.Sleep(10000) for the long 10 seconds. WebBrowser needs a functional Windows message pump to work properly.

Here's a example of how to drive WebBrowser automation asynchronously, without Thread.Sleep or nested message loops.

Community
  • 1
  • 1
noseratio
  • 59,932
  • 34
  • 208
  • 486