C# 如何从我的应用程序在用户默认浏览器中启动 URL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10503909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:06:05  来源:igfitidea点击:

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

c#browserdesktop-application

提问by Aaron Anodide

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.

如何在我的桌面应用程序中有一个按钮,使用户的默认浏览器启动并显示由应用程序逻辑提供的 URL。

采纳答案by Darin Dimitrov

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

回答by neminem

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.

Process.Start([your url]) 确实是答案,除了非常小众的情况。然而,为了完整起见,我会提到我们不久前遇到了这样一个小众案例:如果您尝试打开“file:\” url(在我们的例子中,显示我们的 webhelp 的本地安装副本),在从 shell 启动时,url 的参数被抛出。

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:

除非 Process.Start([your url]) 不符合您的预期,否则您不应该使用丑陋的函数:

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