Windows窗体中的Web浏览器
本文关键字:Web 浏览器 窗体 Windows | 更新日期: 2023-09-27 17:50:03
我试图使一个简单的浏览器在Windows窗体应用程序。我的第一个网站,"http://www.msn.com"是加载在浏览器上的Form_Load。但是当我在textbox1中设置一个有效的url时,什么也没有出现。webBrowser1.Document.Focus();
捕获错误。"对象引用为null或....",null实例的常见问题。
private void Form1_Load(object sender, EventArgs e)
{
myMethod("http://www.msn.com");
}
private void button1_Click(object sender, EventArgs e)
{
myMethod(textbox1.Text);
}
public void myMethod(string url)
{
webBrowser1.DocumentCompleted += browser_DocumentCompleted;
webBrowser1.Navigate(new Uri(url));
webBrowser1.Document.Focus();
}
最新消息
参考@Hans Passant,我终于明白了代码的哪一部分是错误的。
我们在myMethod
中订阅事件webBrowser1.DocumentCompleted += browser_DocumentCompleted;
and we never Unsubscribe from Event
因此,如果webBrowser1.DocumentCompleted
发生,我们将增加订阅次数并触发browser_DocumentComplete
d 不止一次
//constructor
public Form1()
{
InitializeComponent();
//declare webBrowser1 before this
//subscribe only once here
webBrowser1.DocumentCompleted += browser_DocumentCompleted;
//try these two if still fail
//this.webBrowser1.AllowWebBrowserDrop = false;
//this.webBrowser1.ScrollBarsEnabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
myMethod("http://www.msn.com");
}
private void button1_Click(object sender, EventArgs e)
{
myMethod(textbox1.Text);
}
public void myMethod(string url)
{
webBrowser1.Navigate(new Uri(url));
webBrowser1.Document.Focus();
}
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.Text = e.Url.ToString() + " loaded";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//unsubscribe here
webBrowser1.DocumentCompleted -= browser_DocumentCompleted;
webBrowser1.Dispose();
}