【问题标题】:How can I launch a URL in the users default browser from my application?如何从我的应用程序在用户默认浏览器中启动 URL?
【发布时间】:2012-05-17 05:59:04
【问题描述】:

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

【问题讨论】:

    标签: c# browser desktop-application


    【解决方案1】:
     Process.Start("http://www.google.com");
    

    【讨论】:

    【解决方案2】:

    Process.Start([your url]) 确实是答案,除了非常小众的情况。然而,为了完整起见,我会提到我们不久前遇到了这样一个小众案例:如果你试图打开一个“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();
    

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

    【讨论】:

    • 这是非常好的编码
    • 这个答案可以使用更新来包括 Win8 和 Win10。 (如果有人最终实现它,请编辑此答案以包含它!)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2021-10-09
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多