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

Aar*_*ide 30 c# browser desktop-application

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

Dar*_*rov 61

 Process.Start("http://www.google.com");
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这些天您可能还需要将 `UseShellExecute=true` 添加到 ProcessStartInfo:https://github.com/dotnet/runtime/issues/17938 (4认同)

nem*_*nem 20

Process.Start([你的网址])确实是答案,除了非常小众的情况.但是,为了完整起见,我会提到我们不久前遇到了这样一个利基案例:如果你想打开一个"file:\"url(在我们的例子中,要显示我们webhelp的本地安装副本),从shell启动时,url的参数被抛出.

除非您遇到"正确"解决方案的问题,否则我不推荐使用我们相当苛刻的解决方案,看起来像这样:

在按钮的单击处理程序中:

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();
Run Code Online (Sandbox Code Playgroud)

你不应该使用的丑陋功能,除非Process.Start([你的网址])没有达到预期的效果:

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;
}
Run Code Online (Sandbox Code Playgroud)