如何在C#中打开默认浏览器到主页?

时间:2017-04-12 17:30:02

标签: c# browser

以下问题的答案是"如何在C#中打开默认浏览器到URL?"但是如何在不导航到URL的情况下在C#中打开默认浏览器?期望的行为是默认浏览器打开主页,或使用启动行为(例如,在Firefox选项中定义"当Firefox启动时#34;)。

How to open in default browser in C#

1 个答案:

答案 0 :(得分:0)

这应该这样做:

Process p = new Process();
p.StartInfo = new StartInfo(url) {UseShellExecute = true};
p.Start();

编辑:这适用于有效的网址。正如上面的评论所说,这不适用于http://about:home

编辑#2 :我会保留以前的代码,以防它对任何人都有帮助。由于上面的评论我一直在寻找如何做到这一点,并且在行动中并不是那么微不足道,这就是我为了启动默认浏览器而没有导航到任何URL所做的。

using (var assoc = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
{
    using (var cr = Registry.ClassesRoot.OpenSubKey(assoc.GetValue("ProgId") + @"\shell\open\command"))
    {
        string loc = cr.GetValue("").ToString().Split('"')[1];
        // In windows 10 if Microsoft edge is the default browser 
        // loc=C:\Windows\system32\LaunchWinApp.exe, so launch Microsoft Edge manually
        // 'cause didn't figured it out how to launc ME with that exe
        if (Path.GetFileNameWithoutExtension(loc) == "LaunchWinApp")
            Process.Start("explorer", @"shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge");
        else
            Process.Start(loc);
    }
}

我在我的机器(Win10)中进行了测试,并为每个默认的浏览器开关进行了测试。希望现在有所帮助。