Getting WebBrowser Control To Work In Console Application?

依然范特西╮ 提交于 2019-11-30 18:08:46
Sasha Reminnyi

Add STAThread attribute to your main method.

[STAThread]
public static Main()
{
    ...
}

Update: Here what you should do with thread where Browser is created

thread.SetApartmentState(ApartmentState.STA);

Update 2:

If one thread per app:

Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
Hans Passant

A console mode app and WebBrowser are water and fire. You need to follow the single-threaded apartment contract for a thread to use WebBrowser:

  • must be an STA, use [STAThread] on Main() or Thread.SetApartmentState() if you create a thread.
  • must pump a message loop, Application.Run() available in Winforms or WPF.

The second requirement is a hard one for WebBrowser, it won't fire its events if you don't use it. Check this answer for the code to create a thread that runs WB. A GUI app based on Winforms or WPF will always have its main thread already suitable to use WB.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!