任何人都知道使用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等)
由于
答案 0 :(得分:5)
浏览器需要一段时间才能导航到某个页面。 Navigate()方法在导航完成之前不阻止,这将冻结用户界面。 DocumentCompleted事件在完成后触发。您必须将代码移动到该事件的事件处理程序中。
另一个要求是,创建WB的线程是单线程COM组件的快乐之家。它必须是STA并且泵出消息循环。控制台模式应用程序不满足此要求,只有Winforms或WPF项目具有此类线程。检查this answer以获得与控制台模式程序兼容的解决方案。
答案 1 :(得分: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();
}
您也可以使用此示例
答案 2 :(得分:0)
将webbrowser控件拖放到表单并将其AllowNavigation设置为true。然后添加一个按钮控件,在其click事件中,编写webBrowser.Navigate(“http://www.google.co.uk”)并等待页面加载。
如需快速示例,您还可以使用webBrowser.DocumentText = "<html><title>Test Page</title><body><h1> Test Page </h1></body></html>"
。这将显示示例页面。
答案 3 :(得分:0)
试试这个简单的例子
声明:
using System.Windows.Forms;
用法:
WebBrowser b = new WebBrowser();
b.DocumentCompleted += ( sender, e ) => {
WebBrowser brw = ( WebBrowser )sender;
// brw.Document should not null here
// Do anythings with your Document
HtmlElement div = brw.Document.GetElementById( "my_div" );
head.InnerHtml = "Hello World";
//brw.Url should not null here
Console.WriteLine( brw.Url.AbsoluteUri );
// Invoke JS function
brw.Document.InvokeScript( "any_global_function", new object[] { "From C#" } );
};
b.Navigate("http://www.google.co.uk");
答案 4 :(得分:-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