2011-04-19 19 views
5

任何人都知道使用System.Windows.Forms.WebBrowser對象的教程?看看周圍,但找不到一個。我到目前爲止的代碼是(非常複雜):如何使用.net webBrowser對象

System.Windows.Forms.WebBrowser b = new System.Windows.Forms.WebBrowser(); 
b.Navigate("http://www.google.co.uk"); 

,但它實際上並沒有在任何地方瀏覽(iebUrl爲null,b.Document爲null等)

感謝

回答

5

是需要時間的瀏覽器導航到一個頁面。 Navigate()方法執行而不是,直到導航完成,這會凍結用戶界面。 DocumentCompleted事件在完成時觸發。您必須將您的代碼移動到該事件的事件處理程序中。

一個額外的要求是,創建WB的線程是單線程COM組件的快樂之家。它必須是STA並泵送消息循環。一個控制檯模式應用程序不是符合此要求,只有Winforms或WPF項目有這樣的線程。檢查this answer以獲得與控制檯模式程序兼容的解決方案。

0

這是非常簡單的控制。 使用下面的代碼

// Navigates to the URL in the address box when 
// the ENTER key is pressed while the ToolStripTextBox has focus. 
private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.KeyCode == Keys.Enter) 
    { 
     Navigate(toolStripTextBox1.Text); 
    } 
} 

// Navigates to the URL in the address box when 
// the Go button is clicked. 
private void goButton_Click(object sender, EventArgs e) 
{ 
    Navigate(toolStripTextBox1.Text); 
} 

// Navigates to the given URL if it is valid. 
private void Navigate(String address) 
{ 
    if (String.IsNullOrEmpty(address)) return; 
    if (address.Equals("about:blank")) return; 
    if (!address.StartsWith("http://") && 
     !address.StartsWith("https://")) 
    { 
     address = "http://" + address; 
    } 
    try 
    { 
     webBrowser1.Navigate(new Uri(address)); 
    } 
    catch (System.UriFormatException) 
    { 
     return; 
    } 
} 

// Updates the URL in TextBoxAddress upon navigation. 
private void webBrowser1_Navigated(object sender, 
    WebBrowserNavigatedEventArgs e) 
{ 
    toolStripTextBox1.Text = webBrowser1.Url.ToString(); 
} 

您也可以使用這個例子

Extended Web Browser

0

將webbrowser控件拖放到窗體並將其AllowNavigation設置爲true。然後添加按鈕控件並在其單擊事件中,寫入webBrowser.Navigate(「http://www.google.co.uk」)並等待頁面加載。

對於快速樣品,您還可以使用webBrowser.DocumentText = "<html><title>Test Page</title><body><h1> Test Page </h1></body></html>"。這會顯示你的樣本頁面。

-2

如果你只是試圖打開一個瀏覽器,導航我這樣做非常基本的,每個人的答案是非常複雜的。我是很新的C#(1周),我只是做了這樣的代碼:

string URL = "http://google.com"; 
object browser; 
browser = System.Diagnostics.Process.Start("iexplore.exe", URL) 

//This opens a new browser and navigates to the site of your URL variable 
+3

這不回答有關'System.Windows.Forms.WebBrowser'的問題 – 2013-10-15 21:41:46

+0

浪費時間閱讀它。這不使用WebBrowser控件,用於該問題。 – fcm 2016-03-24 19:46:36

+0

@fcm替代答案可能對那些可能會意識到將他們帶到盒子外面的建議的人有所幫助。 – AnthonyVO 2017-06-17 14:34:40

相關問題