是否可以在不使用<windows.h>的情况下在C++中打开URL?



我发现有些编译器不能运行<windows.h>头文件有点棘手。有没有可能在c++中打开URL而不使用<windows.h>?

这是我的代码,但使用<windows.h>
#include <windows.h>
#include <shellapi.h>
using namespace std;

int main(){
ShellExecute(NULL,NULL,"https://ssur.cc/Easy-Way-To-Open-URL-In-CPP",NULL,NULL,SW_SHOW );

return 0;
}

你可以直接声明有问题的函数,让链接器处理它。

但是如果你的编译器在Windows .h上有问题,它可能不支持所有的Windows平台/架构。但是假设编译器使用的调用约定恰好匹配,您可以这样做:

typedef void* M_HINSTANCE;
typedef void* M_HWND; 
#define M_SW_SHOW 5
// should be __stdcall , but if your compiler has trouble with windows.h, then it will probably also have trouble with __stdcall
extern "C" M_HINSTANCE ShellExecuteA(M_HWND   hwnd,
const char* lpOperation,
const char* lpFile,
const char* lpParameters,const char* lpDirectory,
int nShowCmd
);
int main(){
ShellExecuteA(0,0,"https://ssur.cc/Easy-Way-To-Open-URL-In-CPP",0,0,M_SW_SHOW );
return 0;
}

您仍然需要链接到Shell32.lib,并且像我提到的那样,您可能会在某些平台上因不匹配调用约定而获得链接器错误。

或者,您可以尝试将shell作为通用进程启动,如

#include <cstdlib>
int main(){
std::system("cmd.exe /c start https://ssur.cc/Easy-Way-To-Open-URL-In-CPP");
// or something like:
// std::system("explorer.exe https://ssur.cc/Easy-Way-To-Open-URL-In-CPP");
// or on some other non-windows platforms:
// std::system("open https://ssur.cc/Easy-Way-To-Open-URL-In-CPP");
return 0;
}

相关内容

最新更新