指定的强制转换无效-在其他UI线程中访问WebBrowser
本文关键字:UI 其他 线程 WebBrowser 访问 无效 转换 | 更新日期: 2023-09-27 18:25:19
我对我的程序是如何工作的感到困惑。我正在使用线程(从另一个堆栈溢出答案中被告知要这样做),以便TestScenarios()
中的webBrowser2.Navigate(Url);
在GetScenarios()
的while
循环中异步运行。这一切都很好。
现在,我添加了一段代码,以便在WebBrowser
控件中注入并运行一些javascript。然而,每次我呼叫HtmlElement head = webBrowser2.Document
。。。。行,我得到"指定的强制转换无效错误。"
我知道这个错误与WebBrowser
控件在一个单独的UI线程中被访问有关,并且不能以这种方式工作,但我对这到底意味着什么以及如何修复它感到困惑
如果你需要更多的上下文,请发表评论。
public void GetScenarios()
{
new Thread(() =>
{
while() {
...
TestScenarios();
}
}).Start();
}
TestScenarios() {
...
Action action = () =>
{
webBrowser2.Tag = signal;
webBrowser2.Navigate(Url);
webBrowser2.DocumentCompleted -= WebBrowserDocumentCompleted;
webBrowser2.DocumentCompleted += WebBrowserDocumentCompleted;
};
webBrowser2.Invoke(action);
signal.WaitOne();
...
//Run some javascript on the WebBrowser control
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");
}
您正面临这个问题,因为您在加载文档之前就访问了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
事件。
首先……你应该在调试器中逐步了解它,并弄清楚你试图转换的对象是什么……这似乎不是线程问题。
根据您的错误,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
}
通过在中封装JS脚本块来修复它
webBrowser2.Invoke(new Action(() =>
{
//......
}