0

Read a little wiki on COM interface. Going through forums and attempting to absorb all I can, it seems when working in .NET developing browser automating console apps, many frown upon their use.

What is a alternative to my usual

    Dim ie As InternetExplorer

        ie = New InternetExplorer
        ie.Visible = True
        ie.Navigate(website)

I am not sure if best practices type questions are allowed, but I am very curious to know the answer to this. Mainly the alternative and then of course a short why? Thanks guys :)!

1 Answer 1

1

In fact, you can use the Webbrowser control in a multithreading+console/winforms application.

Based on this answer : Run and control browser control in different thread

var html = RunWBControl("http://google.com").Result;

static public Task<string> RunWBControl(string url)
{
    var tcs = new TaskCompletionSource<string>();
    var th = new Thread(() =>
    {
        WebBrowserDocumentCompletedEventHandler completed = null;

        using (WebBrowser wb = new WebBrowser())
        {
            completed = (sndr, e) =>
            {
                tcs.TrySetResult(wb.DocumentText);
                wb.DocumentCompleted -= completed;
                Application.ExitThread();
            };

            wb.DocumentCompleted += completed;
            wb.Navigate(url);
            Application.Run();
        }
    });

    th.SetApartmentState(ApartmentState.STA);
    th.Start();

    return tcs.Task;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering this, going to go ahead in select it. But could you just comment back with just a little bit of the why this would be better? I still am gray on why one would be better than another? I was always under the impression web browser control was to "embed" the browser into your application for the user to well use. Again thank you for you response, really great!
"embed" into form or use it in a background-thread, the important thing to note that you shouldn't block (a tight loop, Thread.Sleep etc.) the thread that created the WebBrowser. If you are only interested in web scraping You can also use html-agility-pack.net

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.