2012-02-14 61 views
0

使用.NET WebBrowser控件,执行HtmlElement的成员非常简单。MSHTML:调用JavaScript对象的成员?

假设有一个名为“player”的JavaScript对象,其成员名为“getLastSongPlayed”;调用这个从.NET WebBrowser控件会去是这样的:

HtmlElement elem = webBrowser1.Document.getElementById("player"); 
elem.InvokeMember("getLastSongPlayed"); 

现在我的问题是:如何实现,使用MSHTML?

由于提前, Aldin

编辑:

我得到它运行起来,看到我的回答如下!

+0

无论我尝试 - 它不起作用。我找不到任何关于这个问题的网络..似乎唯一的方法是通过执行它通过WebBrowsers地址栏执行JavaScript代码.. – Aldin 2012-02-14 15:30:56

+0

因此,webBrowser1已加载的文档在哪里? – 2012-02-14 16:08:42

+0

你是什么意思与“在哪里”? – Aldin 2012-02-14 17:51:29

回答

5

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

这可能会让某人免于未来头痛。大声笑