How can I launch a URL in the users default browse

2019-01-14 20:10发布

问题:

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.

回答1:

 Process.Start("http://www.google.com");


回答2:

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;
}