用winform打开网页浏览器
代码如下:
private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
{
this.webBrowser1.ScriptErrorsSuppressed = true; //禁止弹出脚本错误
//e.Cancel = true; //禁止在新窗口中打开
webBrowser1.Navigate(webBrowser1.StatusText); //跳转到新网页
}
这几句简单的代码可以实现绝大多数的网页在内部打开,但有少部分,因为代码的特殊性不能打开。我们要进行如下加工处理:
我们先写一个方法:
private void SetAllWebItemSelf(HtmlElementCollection items)
{
try
{
foreach (HtmlElement item in items)
{
if (item.TagName.ToLower().Equals("iframe", StringComparison.OrdinalIgnoreCase)==false)
{
try
{
item.SetAttribute("target", "_self");
}
catch
{ }
}
else
{
try
{
HtmlElementCollection fitems = item.Document.Window.Frames[item.Name].Document.All;
this.SetAllWebItemSelf(fitems);
}
catch
{ }
}
}
}
catch
{
}
}
在DocumentCompleted中调用以上方法可以解决以上问题:
代码:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
this.webBrowser1.ScriptErrorsSuppressed = false;
this.SetAllWebItemSelf(this.webBrowser1.Document.All);
}