Search code examples
c#vb.netinterfacecom

Using COM objects for browser automation .net


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 :)!


Solution

  • 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;
    }