Opening the default browser on windows

####The problem I have a windows application with an embedded WebBrowser component. I want to write a function to open the default browser. When the use clicks on a link in the embedded window, I want this link to open in a new window or tab in the default browser (WebBrowser components seem to like to hijack any attempt to open a url).

Windows has no easy way to reliably do this. There are some easy ways to attempt it. These work for some cases but they all failed in certain cases that I tried. The problem is that if there are any existing WebBrowser instances (E.g. an open IE window or a WebBrowser component in the calling application), windows will open the page in that window. That means it will use the WebBrowser component from open browser windows, or from applications that are using the WebBrowser component and have the AllowNavigation property set to true.

####The Solution The following IronPython code will open the default web browser on windows.

Note: python has a webbrowser module in the standard libary but it also fails in the way described above. This code can replace that module on windows.

import clr
import System
import Microsoft
import Microsoft.Win32.Registry as Registry

def get_default_browser():
    try:
        key = Registry.ClassesRoot.OpenSubKey("HTTP\shell\open\command", False)
        browser = key.GetValue(None).ToString().ToLower().Replace("\"", "")
        browser = browser.split('-')[0]
        browser = browser.strip()
        return browser
    finally:
        if key:
            key.Close()
   
def launch_default_browser(destination):
    p = System.Diagnostics.Process()
    p.StartInfo.FileName = get_default_browser()
    p.StartInfo.Arguments = "%s" % destination
    p.Start()

I haven’t tested this much but it works on my windows vm for my for the cases that were failing using the other methods.

You can also hook this code into the Navigating event of the WebBrowser instance of your application so that any links clicked will be opened in a new default browser.

def handle_navigate(sender, event):
    event.Cancel = True
    launch_default_browser(event.Url)

b = System.Windows.Forms.WebBrowser()
b.Navigating += handle_navigate