2013-08-21 8 views
5

URLプロパティが外部Webページに設定されているWinFormsにWebBrowserコントロールがあります。 DocumentCompletedイベントのイベントハンドラもあります。このハンドラの中で、特定の要素を取得しようとしていますが、wb.Document.Bodyはonloadが実行される前にHTMLをキャプチャしているようです。body onloadイベントの実行後にWinForms WebBrowserでHTML本文の内容を取得する

{System.Windows.Forms.HtmlElement} 
    All: {System.Windows.Forms.HtmlElementCollection} 
    CanHaveChildren: true 
    Children: {System.Windows.Forms.HtmlElementCollection} 
    ClientRectangle: {X = 0 Y = 0 Width = 1200 Height = 0} 
    Document: {System.Windows.Forms.HtmlDocument} 
    DomElement: {mshtml.HTMLBodyClass} 
    ElementShim: {System.Windows.Forms.HtmlElement.HtmlElementShim} 
    Enabled: true 
    FirstChild: null 
    htmlElement: {mshtml.HTMLBodyClass} 
    Id: null 
    InnerHtml: "\n" 
    InnerText: null 
    Name: "" 
    NativeHtmlElement: {mshtml.HTMLBodyClass} 
    NextSibling: null 
    OffsetParent: null 
    OffsetRectangle: {X = 0 Y = 0 Width = 1200 Height = 0} 
    OuterHtml: "<body onload=\"evt_Login_onload(event);\" uitheme=\"Web\">\n</body>" 
    OuterText: null 
    Parent: {System.Windows.Forms.HtmlElement} 
    ScrollLeft: 0 
    ScrollRectangle: {X = 0 Y = 0 Width = 1200 Height = 0} 
    ScrollTop: 0 
    shimManager: {System.Windows.Forms.HtmlShimManager} 
    ShimManager: {System.Windows.Forms.HtmlShimManager} 
    Style: null 
    TabIndex: 0 
    TagName: "BODY" 

"<body onload=\"evt_Login_onload(event);\" uitheme=\"Web\">\n</body>"は、JavaScript前のコンテンツです。 evt_Login_onload(event);を実行した後、bodyタグの状態をキャプチャする方法はありますか?

wb.Document.GetElementById("id")も試してみましたが、nullを返します。ここで

答えて

6

は、それがどのように行うことができるかですが、私はいくつかのコメントをインラインで置かれている:

private void Form1_Load(object sender, EventArgs e) 
{ 
    bool complete = false; 
    this.webBrowser1.DocumentCompleted += delegate 
    { 
     if (complete) 
      return; 
     complete = true; 
     // DocumentCompleted is fired before window.onload and body.onload 
     this.webBrowser1.Document.Window.AttachEventHandler("onload", delegate 
     { 
      // Defer this to make sure all possible onload event handlers got fired 
      System.Threading.SynchronizationContext.Current.Post(delegate 
      { 
       // try webBrowser1.Document.GetElementById("id") here 
       MessageBox.Show("window.onload was fired, can access DOM!"); 
      }, null); 
     }); 
    }; 

    this.webBrowser1.Navigate("http://www.example.com"); 
} 
+1

+1私はこの答えを確認することができ、私は 'SyncronizationContext.Current.Postを使用する必要がありませんでしたが、私のために働きました() '私はシングルスレッドを実行しているからです。 –

+0

@StevendeSalas、 'SyncronizationContext.Current.Post'の全目的は、' onload'イベントハンドラから戻り、同じUIスレッド上で非同期的に続行することでした(可能性のある例外は、イベントを発生させるMSHTMLコード内にスローされません)。コードは、それ以来、代わりに 'async' /' await'を使用するように進化しました。[example](http://stackoverflow.com/a/19063643/1768303)。 – Noseratio

+0

私は同様のアプローチを試みましたが、うまくいきませんでした。見てみましょうhttp://stackoverflow.com/questions/22697987/form-b​​ecome-blank-intermittently? – Lijo

関連する問題