HOME> 世界杯北京> C++:手把手教学windows下调用外部exe

C++:手把手教学windows下调用外部exe

2025-06-02 20:57:34     世界杯北京    

参考

https://blog.csdn.net/linjingtu/article/details/53190491 https://blog.csdn.net/u012348774/article/details/60955695

目的

手把手教学windows下调用外部exe。

思路

将外部exe放在本程序同等目录下,然后利用本程序调用外部程序。

步骤

1、获取当前目录

string GetExePath(void)

{

char szFilePath[MAX_PATH + 1]={0};

GetModuleFileNameA(NULL, szFilePath, MAX_PATH);

(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串

return szFilePath;

}

2、调用外部程序

SHELLEXECUTEINFO shExecInfo = {0};

shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);

shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;

shExecInfo.hwnd = NULL;

shExecInfo.lpVerb = "open";

shExecInfo.lpFile = working_path + "demo.exe";//程序所在路径

shExecInfo.lpParameters = "hello world";//程序运行所需的参数,通过argv传入

shExecInfo.lpDirectory = working_path;//程序所在文件夹

shExecInfo.nShow = SW_SHOW;

shExecInfo.hInstApp = NULL;

ShellExecuteEx(&shExecInfo);

//这一句是等待程序结束,再结束main函数

WaitForSingleObject(shExecInfo.hProcess,INFINITE);

此时VS2015中会遇到错误:

CONST CHAR *转换为LPCWSTR

需要进行一下更改:

项目菜单——项目属性(最后一个)——配置属性——常规——项目默认值——字符集,将使用Unicode字符集改为未设置即可。

代码示例

//C

#include

#include

#include

#include

#include

string GetExePath(void)

{

char szFilePath[MAX_PATH + 1]={0};

GetModuleFileNameA(NULL, szFilePath, MAX_PATH);

(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串

return szFilePath;

}

int main()

{

string working_path = GetExePath();

string exe = working_path + "/demo.exe";

string parameter = "hello world!";

{

SHELLEXECUTEINFO shExecInfo = {0};

shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);

shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;

shExecInfo.hwnd = NULL;

shExecInfo.lpVerb = "open";

shExecInfo.lpFile = working_path + "demo.exe";

shExecInfo.lpParameters = "hello world";

shExecInfo.lpDirectory = working_path;

shExecInfo.nShow = SW_SHOW;

shExecInfo.hInstApp = NULL;

ShellExecuteEx(&shExecInfo);

//这一句是等待程序结束,再结束main函数

WaitForSingleObject(shExecInfo.hProcess,INFINITE);

}

return 0;

}