How to force Web Browser control to always open web page in the same window?

走远了吗. 提交于 2019-11-30 09:07:49

Check out: proof-of-concept of .NET System.Windows.Forms.WebBrowser module using source code


My experience about that controls has given me a vision that this issue can tried to be solved in next steps:

  1. always cancel NewWindow event

  2. catch all links clicking

  3. but not all link can be cached this way, so I decided to parse all tags <a> manually on Document Loading Completion

  4. in general, this control is very poor and has been made so by Microsoft deliberately. though there is powerful toolset around Webrowser.Document.HtmlDocument and namespace MSHTML

  5. an example of it's using is HtmlElement.DomElement

    foreach(HtmlElement tag in webBrowser.Document.All)        
    {
      switch (tag.TagName.ToUpper)
      {
        case "A":
        {
          tag.MouseUp += new HtmlElementEventHandler(link_MouseUp);
          break;
        }
      }
    }
    
    void link_MouseUp(object sender, HtmlElementEventArgs e)
    {
      HtmlElement 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)
          {
            // add new tab
          }
          else
          {
            // open in current tab
          }
          break;
        }
        case MouseButtons.Right:
        {
          // show context menu
          break;
        }
      }
    }
    

See more at the first link, that's the source code of main window, there are a lot of different manipulations there!

I found a simple solution that works.

private void WebBrowser1_NewWindow(object sender, System.ComponentModel.CancelEventArgs e) {
    e.Cancel = true;
    WebBrowser1.Navigate(WebBrowser1.StatusText);
}

Why such a complex answer Guys? Abatischev, I'd be curious to see into your brain, should be interesting...

Just try this:

Private Sub WB1_NewWindow(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles WB1.NewWindow
    newUrl = WB1.Url.ToString

    e.Cancel = True
    WB1.Navigate(newUrl)
End Sub

Now you may change the second line into WB2 or any other WebBrowser component in any of your OWN forms.

tester

There is an error in the case MouseBUttons.Left:

Error 1 Control cannot fall through from one case label ('case 1048576:') to another C:\Documents and Settings\ever\My Documents\Visual Studio 2005\Projects\Desarrollo\wApp_SurverMonkey\wApp_SurverMonkey\frmNetcare.cs 64 17 wApp_SurverMonkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!