繁体   English   中英

如何从.NET程序打开Web浏览器? Process.Start()不起作用?

[英]How do I open a web browser from a .NET Program? Process.Start() isn't working?

我有一个URL,我想在默认浏览器中启动它。 我试过两种方法:

Process.Start("http://stackoverflow.com");

...以及使用ShellExecute在另一个问题中详述的那个。

在这两种情况下我都收到错误:Windows无法找到“ http://stackoverflow.com ”。 确保正确键入名称,然后重试。

它不应该试图将其作为文件打开...虽然...从我的理解,它应该将其识别为URL并在默认浏览器中打开它。 我错过了什么?

顺便说一下:OS = Vista,.NET = 3.5

编辑

根据这篇MS知识库文章 ,由于Process.Start默认设置UseShellExecute,它应该启动默认浏览器。

编辑

这是有用的:

System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\IExplore.exe", "http://stackoverflow.com");

不幸的是,它确实没有启动默认浏览器,如果没有在“正常”位置安装IE,它也无法正常工作。 我不知道该怎么做。

更多信息

好的,所以我得到的错误是错误号-2147467259。 看看谷歌,它似乎不是很具描述性。 它可能是文件关联错误或其他什么。

情节变浓

所以我检查了应该具有http的文件关联的注册表项:

KEY_CLASSES_ROOT\http\shell\open\command\default

这是价值:

"C:\Program Files\Mozilla Firefox\firefox.exe" -requestPending -osint -url "%1"

那讲得通。 我实际上将此字符串复制到命令提示符中并将%1替换为http://stackoverflow.com并且它工作并打开了firefox。 我只是不明白为什么Process.Start没有将URL与此命令相关联......

这对我有用:

Process proc = new Process ();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = "http://stackoverflow.com";
proc.Start ();

如果要使用命令类型的自动识别(在本例中为http / browser),请不要忘记UseShellExecute

编辑:如果你Win+R网址吗?

尝试

Process.Start("IExplore.exe http://www.stackoverflow.com");

这将启动Internet Explorer和URL。 Process.Start不检测应用程序/浏览器automaticall.y

当Firefox是默认的Web浏览器时,这是一个严重的问题。

如果我们使用System.Windows.Forms.Help.ShowHelp(null,“ http://microsoft.com ”),则可以在Windows上解决此类错误消息。 但是,在Mono / openSUSE上,Help.ShowHelp无法按预期工作。

好吧,所以它神秘地开始正常工作而不改变任何东西。 我无法解释。 但是,与此同时,我编写了另一种查找和执行默认浏览器的方法。 它有点hacky,但比默认加载IE要好得多:

bool success = false;
RegistryKey httpKey = Registry.ClassesRoot.OpenSubKey(@"http\shell\open\command");
if (httpKey != null && httpKey.GetValue(string.Empty) != null)
{
    string cmd = httpKey.GetValue(string.Empty) as string;
    if (cmd != null)
    {
        try
        {
            if (cmd.Length > 0)
            {
                string[] splitStr;
                string fileName;
                string args;
                if (cmd.Substring(0,1) == "\"")
                {
                    splitStr = cmd.Split(new string[] { "\" " }, StringSplitOptions.None);
                    fileName = splitStr[0] + "\"";
                    args = cmd.Substring(splitStr[0].Length + 2);
                }
                else
                {
                    splitStr = cmd.Split(new string[] { " " }, StringSplitOptions.None);
                    fileName = splitStr[0];
                    args = cmd.Substring(splitStr[0].Length + 1);
                }
                System.Diagnostics.Process.Start(fileName, args.Replace("%1","http://stackoverflow.com"));
                success = true;
            }
        }
        catch (Exception)
        {
            success = false;
        }
    }
    httpKey.Close();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM