2011-11-21 3 views
1

웹 브라우저 컨트롤 (System.Windows.Controls.WebBrowser)이 wB 인 C# WPF 응용 프로그램이 있습니다. 로컬 html 파일과 그로부터 파생 된 일부 정보를 표시합니다. 다음 코드와 함께 (IHTMLElementCollection 같은 IHTMLElementCollection 데이터 =의 hDoc.body.children) 몸이 마지막 줄의 null 말한대로System.Windows.Controls.WebBrowser를 사용하는 NullReferenceException WPF

가 나는 NullReferenceException이 얻을 :

wB.Navigate(new Uri(file, UriKind.Absolute));     
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

내가 할 경우

wB.Navigate(new Uri(file, UriKind.Absolute));     
HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
System.Windows.MessageBox.Show("Loc:" + hDoc.url); 
IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 

모든 것이 정상적으로 작동합니다. 첫 번째 예제에서는 본문이 null이지만 두 번째 예제에서는 null 인 이유는 무엇입니까?

EDIT1 ... 방법은 ... [STAThread]으로 표시됩니다 그래서 나는 동시성 문제가되지 않을 것이라고 생각

Navigate() 방법은 비동기이기 때문이다

답변

3

당신은 그래서 당신은 문서가 이미로드 확신 할 수

wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); 

을 사용해야합니다

private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
{ 
    WebBrowser wb = sender as WebBrowser; 
    HTMLDocument hDoc = (HTMLDocumentClass)wB.Document; 
    IHTMLElementCollection data = hDoc.body.children as IHTMLElementCollection; 
} 
+0

감사합니다! 이것으로 해결됩니다. – Eugene

4

- 당신이 확인하는 두 번째 예에서 MessageBox는 완료하기에 충분한 시간이기 때문에 작동하지만 신뢰할 수는 없습니다.

대신 DocumentCompleted 이벤트에 가입하고 콜백에서 데이터 수집을 수행해야합니다.

관련 문제