Ald*_*din 0 javascript c# browser mshtml
使用.NET WebBrowser控件,执行HtmlElement的成员非常简单.
假设有一个名为"player"的JavaScript对象,其成员名为"getLastSongPlayed"; 从.NET WebBrowser控件调用它将是这样的:
HtmlElement elem = webBrowser1.Document.getElementById("player");
elem.InvokeMember("getLastSongPlayed");
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:如何使用mshtml实现这一目标?
在此先感谢,阿尔丁
编辑:
我把它运行起来,看下面的答案!
最后!! 我把它搞定了!
之所以如此
System.InvalidCastException
Run Code Online (Sandbox Code Playgroud)
每当我尝试引用mshtml.IHTMLDocument2的parentWindow和/或将其分配给mshtml.IHTMLWindow2窗口对象时,抛出的就是Threading.
对于某些人,我不知道,因为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.
}
}
Run Code Online (Sandbox Code Playgroud)
我们现在还可以引用mshtml.IHTMLDocument2对象的parentWindow并执行站点脚本和/或我们自己的脚本(记住它必须在STA线程上):
mshtml.IHTMLWindow2 window = doc.parentWindow;
window.execScript("AScriptFunctionOrOurOwnScriptCode();", "javascript");
Run Code Online (Sandbox Code Playgroud)
这可能会使某人在将来免于头痛.大声笑
归档时间: |
|
查看次数: |
5179 次 |
最近记录: |