开发者

How to simulate a "open link on new window" on a C# WebBrowser?

I just found out that to simulate a click I can call element.InvokeMember("click"); where element is an HtmlElement. But what I actually need is to open the link in a new window, but not on the default br开发者_运维技巧owser but on another WebBrowser I would create in my program. Sometimes it works to just get the href attribute by calling element.GetAttribute("href"); and then just navigating to the returned URL, but some picky web pages won't work this way, I assume something to do with cookies and sessions.


Just handle the NewWindow2 event, create a form/tab that has a webbrowser on it, and use the webbrowser as the target of the new window request. Check http://www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx for an example.


System.Windows.Forms.WebBrowser is a very crippled control and one of its biggest problem - supporting of multi-tabbing. It doesn't support it at all.

I spent tons of time to try make it work properly but got no sufficient success, so recommend you to try 3rd party control instead.

Workaround: subscribe to click event of each <a> on page (or some of them you need) and create a new windows manually. For example, see how does it implemented in dotBrowser: 1 2

foreach (HtmlElement tag in webBrowser.Document.All)
{
    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)
{
    mshtml.HTMLAnchorElementClass a = (mshtml.HTMLAnchorElementClass)((HtmlElement)sender).DomElement;
    switch (e.MouseButtonsPressed)
    {
        case MouseButtons.Left:
        {
            // open new tab
            break;
        }
        case MouseButtons.Right:
        {
            // open context menu
            break;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜