FINALLY !!我知道它运行起来了!
的原因
System.InvalidCastException
是被抛出,每当我试图引用parentWindow的mshtml.IHTMLDocument2和/或指定给一个mshtml.IHTMLWindow2窗口对象曾与线程做。
对于某些我未知的事情,理由似乎是mshtml.IHTMLWindow的COM对象在另一个必须是单线程公寓(STA)状态的线程上运行。
所以诀窍是,调用/执行另一个线程与STA状态所需的一段代码。
下面是一个示例代码:
SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer
bool _isRunning = false;
private void IE_DocumentComplete(object pDisp, ref obj URL)
{
//Prevent multiple Thread creations because the DocumentComplete event fires for each frame in an HTML-Document
if (_isRunning) { return; }
_isRunning = true;
Thread t = new Thread(new ThreadStart(Do))
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
private void Do()
{
mshtml.IHTMLDocument3 doc = this.IE.Document;
mshtml.IHTMLElement player = doc.getElementById("player");
if (player != null)
{
//Now we're able to call the objects properties, function (members)
object value = player.GetType().InvokeMember("getLastSongPlayed", System.Reflection.BindingFlags.InvokeMethod, null, player, null);
//Do something with the returned value in the "value" object above.
}
}
现在我们也能引用mshtml.IHTMLDocument2对象的parentWindow并执行脚本的网站和/或我们自己的(记得一定要上的STA线程):
mshtml.IHTMLWindow2 window = doc.parentWindow;
window.execScript("AScriptFunctionOrOurOwnScriptCode();", "javascript");
这可能会让某人免于未来头痛。大声笑
无论我尝试 - 它不起作用。我找不到任何关于这个问题的网络..似乎唯一的方法是通过执行它通过WebBrowsers地址栏执行JavaScript代码.. – Aldin 2012-02-14 15:30:56
因此,webBrowser1已加载的文档在哪里? – 2012-02-14 16:08:42
你是什么意思与“在哪里”? – Aldin 2012-02-14 17:51:29