views:

127

answers:

2

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 browser 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.

+1  A: 

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;
        }
    }
}
abatishchev
But, what would be the code in the "// open new tab" line, since that's where you actually open the link in a new window?
jsoldi
@jsoldi: Follow link #2 above. Me in your case - would create a new form with constructor accepting a string (url). That form would create a new WebBrowser and navigate it to that url.
abatishchev
Well, the problem with that is that some pages uses cookies and stuff like that that won't let me just copy the link and open it on a new window. That's what I was doing before until I found out that on ebay, copying the href of the "Next" link (the one that would send me to the next page of results) and then navigating to it in a new window would land me always on the first page. No idea why. I suspect it has something to do with sessions and cookies.
jsoldi
A: 

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.

Sheng Jiang 蒋晟