【发布时间】:2012-05-17 05:59:04
【问题描述】:
如何在我的桌面应用程序中设置一个按钮,使用户的默认浏览器启动并显示应用程序逻辑提供的 URL。
【问题讨论】:
标签: c# browser desktop-application
如何在我的桌面应用程序中设置一个按钮,使用户的默认浏览器启动并显示应用程序逻辑提供的 URL。
【问题讨论】:
标签: c# browser desktop-application
Process.Start("http://www.google.com");
【讨论】:
UseShellExecute=true 添加到 ProcessStartInfo:github.com/dotnet/runtime/issues/17938
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;
}
【讨论】: