如何在 C 中打开 Windows 中的默认 Web 浏览器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3037088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open the default web browser in Windows in C?
提问by Daniel
In C in Windows, how do I open a website using the default browser? In Mac OS X, I do system("open http://url");
在 Windows 中的 C 中,如何使用默认浏览器打开网站?在 Mac OS X 中,我做system("open http://url");
回答by lornova
You have to use ShellExecute()
.
你必须使用ShellExecute()
.
The C code to do that is as simple as:
执行此操作的 C 代码非常简单:
ShellExecute(NULL, "open", "http://url", NULL, NULL, SW_SHOWNORMAL);
This was documented by Microsoft Knowledge Base article KB 224816, but unfortunately the article has been retired and there's no archived version of it.
Microsoft 知识库文章 KB 224816 对此进行了记录,但不幸的是,该文章已弃用,并且没有存档版本。
回答by Sjoerd
In Windows, you can use start http://url
on the command line to open an URL in the default browser. However, this seems to be specific to the command prompt and is not a real executable, so I don't think you can start it from your C/C++ program.
在 Windows 中,您可以使用start http://url
命令行在默认浏览器中打开 URL。但是,这似乎特定于命令提示符,并不是真正的可执行文件,因此我认为您不能从 C/C++ 程序启动它。
回答by Abraham Hernandez
To open a URL in your default browser you could use shell commands and system()
like this:
要在默认浏览器中打开 URL,您可以使用 shell 命令,system()
如下所示:
#include <stdlib.h>
int main(void)
{
system("open https://example.com");
}
open
is the default command to open stuff on MacOS, but what happens when you want to open a URL on Windows, Linux, or another operating system?
open
是在 MacOS 上打开内容的默认命令,但是当您想在 Windows、Linux 或其他操作系统上打开 URL 时会发生什么?
Well, you will need to change that open
command.
好吧,您将需要更改该open
命令。
On Linux
在 Linux 上
xdg-open <link>
On Windows
在 Windows 上
start <link>
On MacOS
在 MacOS 上
open <link>
But there is good news, you don't need to handle that, I already created a module/package/libraryand you can install it using CLIB. It is cross-platform, already handle the operating systems stuff, and it is super easy to include it on your project.
但是有个好消息,你不需要处理那个,我已经创建了一个模块/包/库,你可以使用CLIB安装它 。它是跨平台的,已经处理了操作系统的事情,并且非常容易将它包含在您的项目中。
Installation
安装
$ clib install abranhe/opener.c
Usage
用法
#include "opener.h"
int main(void)
{
opener("https://example.com");
return 0;
}
Since it is written using the shell commands, you are also able to open local directories.
由于它是使用 shell 命令编写的,因此您还可以打开本地目录。
// Open current directory
opener(".");