【问题标题】:.net Open link from WebBrowser Control in a new Tab in IE.net 在 IE 的新选项卡中从 WebBrowser 控件打开链接
【发布时间】:2023-03-05 12:17:01
【问题描述】:
我的应用程序中有一个 Web 浏览器控件,其中包含以下链接:
<html>
<body>
<a href="http://www.google.com" target="abc">test</a>
</body>
</html>
每次单击此链接时,它都会在 IE 的新窗口中打开,而不是在新选项卡中打开。我尝试直接在 IE 中加载这个 html - 然后它会在新选项卡中正确打开。
我还配置了 IE 设置以在新选项卡而不是新窗口中打开链接。
谁能帮我在新标签页中加载来自网络浏览器控件的链接?
谢谢!
【问题讨论】:
标签:
html
hyperlink
webbrowser-control
【解决方案1】:
如果您已指定您是使用 Winforms 还是 WPF 作为 Web 浏览器控件,甚至是您使用的语言(C#、VB、F# 等)但假设您使用的是 winforms 和 C#,这将很有帮助会工作的。
您只需取消新窗口事件并自己处理导航和标签内容。
这是一个完整的示例。
using System.ComponentModel;
using System.Windows.Forms;
namespace stackoverflow2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.NewWindow += WebBrowser1_NewWindow;
this.webBrowser1.Navigated += Wb_Navigated;
this.webBrowser1.DocumentText=
"<html>"+
"<head><title>Title</title></head>"+
"<body>"+
"<a href = 'http://www.google.com' target = 'abc' > test </a>"+
"</body>"+
"</html>";
}
private void WebBrowser1_NewWindow(object sender, CancelEventArgs e)
{
e.Cancel = true; //stop normal new window activity
//get the url you were trying to navigate to
var url= webBrowser1.Document.ActiveElement.GetAttribute("href");
//set up the tabs
TabPage tp = new TabPage();
var wb = new WebBrowser();
wb.Navigated += Wb_Navigated;
wb.Size = this.webBrowser1.Size;
tp.Controls.Add(wb);
wb.Navigate(url);
this.tabControl1.Controls.Add(tp);
tabControl1.SelectedTab = tp;
}
private void Wb_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
tabControl1.SelectedTab.Text = (sender as WebBrowser).DocumentTitle;
}
}
}