问题描述
|
有谁知道使用System.Windows.Forms.Webbrowser对象的教程吗?环顾四周,却找不到。到目前为止,我的代码非常复杂:
System.Windows.Forms.Webbrowser b = new System.Windows.Forms.Webbrowser();
b.Navigate(\"http://www.google.co.uk\");
但实际上并不会在任何地方导航(即b.Url为null,b.Document为null等)
谢谢
解决方法
浏览器导航到页面需要花费时间。在导航完成之前,Navigate()方法不会阻塞,这将冻结用户界面。完成后会触发DocumentCompleted事件。您必须将代码移到该事件的事件处理程序中。
另一个要求是,创建WB的线程对于单线程COM组件来说是一个幸福的家。它必须是STA并泵送消息循环。控制台模式应用程序不满足此要求,只有Winforms或WPF项目具有此类线程。检查此答案以获取与控制台模式程序兼容的解决方案。,这是非常简单的控制。
使用以下代码
// 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();
}
您也可以使用此示例
扩展网络浏览器,将一个Web浏览器控件拖放到一个窗体并将其AllowNavigation设置为true。然后添加按钮控件,并在其click事件中编写webBrowser.Navigate(\“ http://www.google.co.uk \”)并等待页面加载。
对于快速样品,您也可以使用webBrowser.DocumentText = \"<html><title>Test Page</title><body><h1> Test Page </h1></body></html>\"
。这将显示示例页面。,如果您只是想打开浏览器并导航,我正在做的很基本,那么每个人的答案都非常复杂。.我对C#刚起步(一周后),我只是做了这段代码:
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