在c#中插入webbrowser时出错

时间:2015-09-28 09:45:30

标签: c# multithreading webbrowser-control panel

我正在开发一个应用程序,我需要在panl中插入一个webbrowser。这样做我在desginer代码中得到错误"无法获得' WebBrowser'控制。不支持无窗口的ActiveX控件。"我已经把代码放在STSthread中运行了。但之后我得到错误的#34;交叉线程。"

Thread newThread = new Thread(newThreadStart(MethodToCallCOMMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
private void MethodToCallCOMMethod()
        {
            this.webBrowser1 = new System.Windows.Forms.WebBrowser();
            this.webBrowser2 = new System.Windows.Forms.WebBrowser();

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MethodInvoker(delegate
                                {
                                    this.p_bottom.Controls.Add(this.webBrowser2);

                                }));
            }
            else
            {
                this.p_bottom.Controls.Add(this.webBrowser2);
            }
        }

使用invokerequired后我仍然得到"交叉线程错误:-control''从另一个线程访问它是在c#"中创建的,如何解决它??请帮助我。

1 个答案:

答案 0 :(得分:3)

问题是你是在另一个线程中创建WebBrowsers,一般来说你永远不应该在gui线程之外创建或编辑控件。

因此要么在其他地方(在GUI线程中)创建webBrowser1和2,要么将代码放在MethodInvoker委托(在GUI线程中运行)中

如果它显示the current thread is not in a single-threaded apartment,那么您的主要功能看起来不像这样(默认情况下VS创建的)或者您尝试从另一个线程创建它们:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}