C#Web浏览器导航

时间:2011-05-10 11:58:38

标签: c# visual-studio-2010 windows-forms-designer

我的应用程序上打开了浏览器,使用默认的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数组,而浏览器是一组要在不同屏幕上加载的网页。

1 个答案:

答案 0 :(得分:3)

如果我没错,因为'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