How can I launch a URL in the users default browse

2019-01-14 20:35发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2019-01-14 20:58
 Process.Start("http://www.google.com");
查看更多
Explosion°爆炸
3楼-- · 2019-01-14 21:05

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;
}
查看更多
登录 后发表回答