0

I am trying to use WebBrowser since I need to interact with some elements created via JS and not present in the original response.

I have read other questions where the event is not being fired because the single-threaded program is waiting for a read key or something similar, and thus the event cannot be fired.

However, in my case, it is just finishing the program and the Client_DocumentCompleted method is never entered.

[STAThread]
static void Main(string[] args)
{
    Helper();
}

static void Helper()
{

    WebBrowser client = new WebBrowser();
    client.DocumentCompleted += Client_DocumentCompleted;
    client.AllowNavigation = true;
    client.Navigate("https://www.google.com/");
}

private static void Client_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    WebBrowser client = (WebBrowser)sender;
    while (client.ReadyState != WebBrowserReadyState.Complete)
    {
        Console.WriteLine(client.ReadyState);
    }
    string htmlCode = client.Document.ToString();
    Console.Write(htmlCode);

    Console.ReadKey();
}

I tried doing the WebBrowser interaction in a separate thread without success.

var t = new Thread(Helper);
t.SetApartmentState(ApartmentState.STA);
t.Start();

Edit: Updated to include the [STAThread] attribute which was already present in my solution

havan
  • 164
  • 2
  • 11

1 Answers1

1

You should add STAThread attribute to your Main:

[STAThread]
static void Main(string[] args)
{
    //...
}

This is required when using COM components

Sunil
  • 3,404
  • 10
  • 23
  • 31
  • I do have it, it just was not copied over. Without this attribute, an exception is thrown when initializing the WebBroswer – havan Feb 28 '18 at 08:47
  • I copy pasted your code in to Visual Studio and it does fire the event (After I added STAThread). So when you say its already there, then you may need to try Clean Solution / Rebuild. Hope it helps. – Sunil Feb 28 '18 at 09:43
  • I tried cleaning and rebuilding without success. I also created a new console app. The program just exits without the event being triggered. I am using the reference to Systems.Windows.Forms. I also tried doing a while loop after navigating, and it kept saying that the ready state is unitialized – havan Feb 28 '18 at 10:09
  • Wait! you are checking ReadyState in DocumentCompleted, means you are reaching there already? – Sunil Feb 28 '18 at 10:13
  • The answer to [this question](https://stackoverflow.com/questions/2747379/net-c-webbrowser-control-navigate-does-not-load-targeted-url) is working out just fine for me. Other than doing the Application.Run bit, I do not understand what the difference is. – havan Feb 28 '18 at 10:21
  • No, I meant checking ReadyState right after client.Navigate() inside of the Helper method. Sorry for not clarifying that. – havan Feb 28 '18 at 10:22