Link to home
Create AccountLog in
Avatar of deanlee17
deanlee17

asked on

WPF browser control link opening

Hi guys,

I have a WPF app with the browser control dropped onto a tab. All works well until the website being displayed wants to open a link in a new window, this then breaks out of my app and opens a browser window. How can I open all links within the browser control inside my app?

Found the below code and gave it a try but no joy, anyone got a simple solution?

dynamic browser = sender;
            dynamic activeElement = browser.Document.activeElement;
            var link = activeElement.ToString();
            // this is new Window,if you want open in current page,only change the browser.Source and Cancel the event
            WebBrowser_Sourcing_Netcomponents_Enquiry.Source = new Uri(link);

            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.ToString());
            }
            finally
            {
                e.Cancel = true;
            }

Open in new window


Cheers,
Dean
Avatar of fredvr666
fredvr666

I used it like this:
this.WebBrowser1.Navigate("http://www.google.com");
Avatar of deanlee17

ASKER

Hi, how does that capture links clicked on a page?
You right I tried this in a project:
add Reference|Extensions: Microsoft.mshtml
In the MainWindow add
WebBrowser1.LoadCompleted += new LoadCompletedEventHandler(WebBrowser1_LoadCompleted);

 void WebBrowser1_LoadCompleted(object sender, NavigationEventArgs e)
        {
            //Ricci Gian Maria
            mshtml.HTMLDocument HTMLdoc = WebBrowser1.Document as mshtml.HTMLDocument;
            foreach (mshtml.IHTMLElement item in HTMLdoc.links)
            {
                var targetAttributeValue = item.getAttribute("target");
                if (targetAttributeValue != null)
                {
                    item.setAttribute("target", "_self");
                }
            }
        }

I tried it this is working
Ok I got the attached error:
error.png
rename the WebBrowser1_LoadCompleted
to WebBrowser_Sourcing_Netcomponents_Enquiryebrowser_LoadCompleted
Attached.

My program still runs, but the web control isn't even visible.

Thanks
error.png
put the navigate after the loadcompleted init
Put it on a button command, still no joy there.
ASKER CERTIFIED SOLUTION
Avatar of fredvr666
fredvr666

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Perfect, thanks.