指定的强制转换无效 - 在不同的UI线程中访问WebBrowser

时间:2013-07-29 16:04:42

标签: c# multithreading webbrowser-control

我很难理解我的程序是如何工作的。我正在使用线程(被告知从另一个Stack Overflow应答中这样做),以便webBrowser2.Navigate(Url);中的TestScenarios()在内部异步运行<{1}}中的while循环。这一切都很好。

现在,我添加了一大块代码来注入并运行GetScenarios()控件中的一些javascript。但是,每当我调用WebBrowser ....行时,我都会收到“指定演员阵容无效错误。”

我知道这个错误与在一个单独的UI线程中访问的HtmlElement head = webBrowser2.Document控件有关,而且无法以这种方式工作,但我对这究竟是什么意思以及我如何能够感到困惑解决它。

如果您需要更多上下文,请发表评论。

WebBrowser

3 个答案:

答案 0 :(得分:2)

您遇到此问题,因为在文档加载之前您正在访问webBrowser的元素。你应该移动这段代码

HtmlElement head = webBrowser2.Document.GetElementsByTagName("head")[0];
                    HtmlElement scriptEl = webBrowser2.Document.CreateElement("script");
                    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
                    element.text = "function sayHello() { alert('hello') }";
                    head.AppendChild(scriptEl);
                    webBrowser2.Document.InvokeScript("sayHello");

WebBrowserDocumentCompleted

事件。

答案 1 :(得分:1)

首先......你应该在调试器中逐步完成它并弄清楚你想要投射的对象是什么......这似乎不是一个线程问题。

根据您的错误webBrowser2.Document.GetElementsByTagName("head")[0]无法转换为HtmlElement

你也可以尝试这样的东西来看看对象是什么......

var head = webBrowser2.Document.GetElementsByTagName("head")[0] as HtmlElement;
if (head == null)
{
    Console.WriteLine(typeof(head);  // output the object type somehow
}

答案 2 :(得分:0)

通过将JS脚本块包装在:

中来管理修复它
webBrowser2.Invoke(new Action(() =>
{
     //......
}