2012-02-14 5 views
0

.NET WebBrowser 컨트롤을 사용하면 HtmlElement의 멤버를 실행하는 것이 매우 간단합니다.MSHTML : 자바 스크립트 개체의 멤버를 호출 하시겠습니까?

"getLastSongPlayed"라는 멤버가있는 "player"라는 JavaScript 객체가 있다고 가정합니다. 이런 식으로 뭔가를 갈 것이라고는 .NET 웹 브라우저 컨트롤에서이 전화 :

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

지금 내 질문은 : 어떻게 MSHTML을 사용하는 것을 달성합니까? 사전에

감사합니다, 알딘

편집 : 나는 그것을하고 실행은, 내 대답은 아래를 참조있어

!

+0

아무리 노력해도됩니다. 작동하지 않습니다. 이 문제에 관한 웹에서 아무것도 찾을 수 없습니다. 유일한 방법은 WebBrowsers 주소 표시 줄을 통해 실행하여 JavaScript 코드를 실행하는 것 같습니다. – Aldin

+0

그래서 webBrowser1이로드 한 문서는 어디에 있습니까? –

+0

"어디"인가요? – Aldin

답변

5

마침내 !! 나는 그것을 달리고 달린다!

내가 스레딩 함께 할 가지고 있던 mshtml.IHTMLDocument2의 parentWindow를 참조 및/또는 mshtml.IHTMLWindow2 창 개체에 할당하려고 할 때마다, 발생 된

System.InvalidCastException 

이유.

일부 사용자에게는 mshtml.IHTMLWindow의 COM 개체가 STA (Single-Threaded Apartment) 상태 여야하는 다른 스레드에서 작동하고있는 것으로 보이는 이유가 있습니다.

그래서 트릭은 STA 상태로 다른 스레드에서 필요한 코드를 호출하거나 실행하는 것이 었습니다. 여기

은 샘플 코드이다 : 우리는 지금 사이트 스크립트 및/또는 mshtml.IHTMLDocument2 객체의 parentWindow을 참조하고 실행할 또한 수있어

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. 
    } 
} 

우리 (AN STA에 있어야 기억 자신의 스레드) :

mshtml.IHTMLWindow2 window = doc.parentWindow; 

window.execScript("AScriptFunctionOrOurOwnScriptCode();", "javascript"); 

이것은 앞으로 두통을 피할 수 있습니다. lol