windows 从我的应用程序启动网页
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/153046/
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
Launch web page from my application
提问by Matt
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.
好吧,这可能有一个非常简单的答案,但我以前从未尝试过:如何从应用程序中启动网页?您知道,“单击此处转到我们的常见问题解答”,然后他们会启动默认的 Web 浏览器并转到您的页面。我正在 Windows 中使用 C/C++,但如果有更广泛、更便携的方式来做,我也想知道。
回答by Patrick Desjardins
#include <windows.h>
void main()
{
ShellExecute(NULL, "open", "http://yourwebpage.com",
NULL, NULL, SW_SHOWNORMAL);
}
回答by Brian Ensink
I believe you want to use the ShellExecute() function which should respect the users choice of default browser.
我相信您想使用 ShellExecute() 函数,该函数应该尊重用户对默认浏览器的选择。
回答by twk
Please read the docsfor ShellExecute closely. To really bulletproof your code, they recommend initializing COM. See the docs here, and look for the part that says "COM should be initialized as shown here". The short answer is to do this (if you haven't already init'd COM):
请仔细阅读ShellExecute的文档。为了真正防弹您的代码,他们建议初始化 COM。请参阅此处的文档,并查找“COM 应按此处所示进行初始化”的部分。简短的回答是这样做(如果您还没有初始化 COM):
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE)
回答by nico
For the record (since you asked for a cross-platform option), the following works well in Linux:
作为记录(因为您要求跨平台选项),以下在 Linux 中运行良好:
#include <unistd.h>
#include <stdlib.h>
void launch(const std::string &url)
{
std::string browser = getenv("BROWSER");
if(browser == "") return;
char *args[3];
args[0] = (char*)browser.c_str();
args[1] = (char*)url.c_str();
args[2] = 0;
pid_t pid = fork();
if(!pid)
execvp(browser.c_str(), args);
}
Use as:
用于:
launch("http://example.com");
回答by zakker
You can use ShellExecute function. Sample code:
您可以使用 ShellExecute 函数。示例代码:
ShellExecute( NULL, "open", "http://stackoverflow.com", "", ".", SW_SHOWDEFAULT );
回答by Sig Gam
For some reason, ShellExecute do not work sometimes if application is about to terminate right after call it. We've added Sleep(5000) after ShellExecute and it helps.
出于某种原因,如果应用程序在调用后立即终止,ShellExecute 有时不起作用。我们在 ShellExecute 之后添加了 Sleep(5000) 并且它有帮助。