Feature Post

Top

WebBrowser control in a Console app

A few notes for those trying to question, how to run WebBrowser in a Console application?
  • WebBrowser control is primarily intended for Forms based app. 
  • Console app is not on STA(Single Threaded Apartment - which offers a message-based communication between OS and application for dealing with multiple objects running concurrently) by default; which means no message pumping, which means no events are going to be fired - so don't be shockingly surprised, must if you go that way!

If must, you choose Console, then following may be the options:

  • You can use a WebClient, or HttpWebRequest to request a page and parse response manually.
  • You can write your own message pump by adding a GetMessage/DispatchMessage in a while loop; and then you add the switch cases for the Message that you are looking for. Its goes something like:

while (GetMessage(&msg, NULL, 0, 0)) {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
}
  • Add a Form(with WebBrowser control) to your console app and do Application.Run(YourForm), for it to dispatch the events.
  • Show the Form in another thread with its own message pump; probably a hidden form.

[STAThread]
static void Main(string[] args)
{
    System.Threading.Thread thdBrowser = new System.Threading.Thread(RunFormInParallel);
    thdBrowser.SetApartmentState(System.Threading.ApartmentState.STA);
    thdBrowser.Start();

    Console.ReadLine();
}

private static void RunFormInParallel()
{
    Form form1 = new Form();//new form

    WebBrowser webBrowser = new WebBrowser();//create a browser
    webBrowser.Dock = DockStyle.Fill;
    webBrowser.Url = new Uri("http://www.bing.com");

    form1.Controls.Add(webBrowser);//add to form
    
    Application.Run(form1);//run
} 

Enjoy coding!

1 comment:

  1. Thanks for sharing.. this was very helpful

    ReplyDelete