How can I launch a URL in the users default browser from my application?
Asked Answered
P

2

36

How can I have a button in my desktop application that causes the user's default browser to launch and display a URL supplied by the application's logic.

Poirer answered 8/5, 2012 at 17:59 Comment(0)
C
70
 Process.Start("http://www.google.com");
Cougar answered 8/5, 2012 at 18:0 Comment(1)
Note these days you might also need to add UseShellExecute=true to the ProcessStartInfo: github.com/dotnet/runtime/issues/17938Wanigan
B
22

Process.Start([your url]) is indeed the answer, in all but extremely niche cases. For completeness, however, I will mention that we ran into such a niche case a while back: if you're trying to open a "file:\" url (in our case, to show the local installed copy of our webhelp), in launching from the shell, the parameters to the url were thrown out.

Our rather hackish solution, which I don't recommend unless you encounter a problem with the "correct" solution, looked something like this:

In the click handler for the button:

string browserPath = GetBrowserPath();
if (browserPath == string.Empty)
    browserPath = "iexplore";
Process process = new Process();
process.StartInfo = new ProcessStartInfo(browserPath);
process.StartInfo.Arguments = "\"" + [whatever url you're trying to open] + "\"";
process.Start();

The ugly function that you shouldn't use unless Process.Start([your url]) doesn't do what you expect it's going to:

private static string GetBrowserPath()
{
    string browser = string.Empty;
    RegistryKey key = null;

    try
    {
        // try location of default browser path in XP
        key = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false);

        // try location of default browser path in Vista
        if (key == null)
        {
            key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http", false); ;
        }

        if (key != null)
        {
            //trim off quotes
            browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
            if (!browser.EndsWith("exe"))
            {
                //get rid of everything after the ".exe"
                browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
            }

            key.Close();
        }
    }
    catch
    {
        return string.Empty;
    }

    return browser;
}
Boxer answered 8/5, 2012 at 18:33 Comment(2)
This is extremely nice codingMasonry
This answer could use an update to include Win8 and Win10. (If someone ends up implementing it, edit this answer to include it!)Cobnut

© 2022 - 2024 — McMap. All rights reserved.