2011-04-19 22 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

相关问题