Visual Studio 2010 - C# Web 浏览器导航

本文关键字:Web 浏览器 导航 Studio 2010 Visual | 更新日期: 2023-09-27 17:56:02

我的应用程序上有打开的浏览器,它们使用默认的Web浏览器加载数据。

//Set the function and display the browsers we're using (per screen)
browsers[index].Width = screens[index].Bounds.Width;
browsers[index].Height = screens[index].Bounds.Height;
browsers[index].Location = new System.Drawing.Point(screens[index].Bounds.X, screens[index].Bounds.Y);
browsers[index].Navigate(new Uri(lines[index]));
browsers[index].Show();

现在我的问题是,当您单击页面上的链接时,它会离开我的应用程序并完全打开一个新的浏览器。有什么办法可以摆脱这种情况吗?

行包含 URL 数组,浏览器是在不同屏幕上加载的网页数组。

Visual Studio 2010 - C# Web 浏览器导航

如果我没错的话,这是因为"TARGET = "_blank",我会尝试在呈现内容之前将其从标签中删除。

private void Browser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
    var webBrowser = (WebBrowser)sender;
    if (webBrowser.Document != null)
    {
        foreach (HtmlElement tag in webBrowser.Document.All)
        {
            if (tag.Id == null)
            {
                tag.Id = String.Empty;
                switch (tag.TagName.ToUpper())
                {
                    case "A":
                    {
                        tag.MouseUp += new HtmlElementEventHandler(link_MouseUp);
                        break;
                    }
                }
            }
        }
    }
}

private void link_MouseUp(object sender, HtmlElementEventArgs e)
{
    var link = (HtmlElement)sender;
    mshtml.HTMLAnchorElementClass a = (mshtml.HTMLAnchorElementClass)link.DomElement;
    switch (e.MouseButtonsPressed)
    {
        case MouseButtons.Left:
        {
            if ((a.target != null && a.target.ToLower() == "_blank") || e.ShiftKeyPressed || e.MouseButtonsPressed == MouseButtons.Middle)
            {
                AddTab(a.href);
            }
            else
            {
                CurrentBrowser.TryNavigate(a.href);
            }
            break;
        }
        case MouseButtons.Right:
        {
            CurrentBrowser.ContextMenuStrip = null;
            var contextTag = new ContextTag();
            contextTag.Element = a;
            contextHtmlLink.Tag = contextTag;
            contextHtmlLink.Show(Cursor.Position);
            break;
        }
    }
}

来源:http://stackoverflow.com/questions/5312275/open-new-web-page-in-new-tab-in-webbrowser-control