Getting error on inserting webbrowser inside panel in c#

一世执手 提交于 2019-12-08 14:08:46

问题


i am developing an application in which i require to insert a webbrowser inside a panl.while doing this i am getting error inside desginer code "Unable to get the window handle for the 'WebBrowser' control. Windowless ActiveX controls are not supported."for which i have put the code to run it inside STSthread.but after that i am getting error of "cross thread.."

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

after using invokerequired i am still getting "cross thread error:-control'' access from another thread that it was created in c#",how to solve it..?please help me.


回答1:


The problem is that you are creating the WebBrowsers in a different thread, in general you should never create or edit controls outside the gui thread.

So either create the webBrowser1 and 2 somewhere else (in the GUI Thread) or put the code inside the MethodInvoker delegate (which runs in the GUI Thread)

If it says the current thread is not in a single-threaded apartment then either your Main function doesn't look like this (what VS creates by default) or you tried to create them from another thread:

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


来源:https://stackoverflow.com/questions/32820005/getting-error-on-inserting-webbrowser-inside-panel-in-c-sharp

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