简介
ShellExecute的功能是运行一个外部程序(或者是打开一个已注册的文件、打开一个目录、打印一个文件等等),并对外部程序有一定的控制。有几个API函数都可以实现这些功能,但是在大多数情况下ShellExecute是更多的被使用的,同时它并不是太复杂。
示例
- 宿主程序
#include "stdafx.h"
#include "windows.h "
#include "shellapi.h "
int main()
{
char filePath[MAX_PATH];
GetCurrentDirectory(1000, filePath); //得到当前工作路径
strcat_s(filePath, "\\ToolConsole.exe"); //文件名
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = _T("open");
ShExecInfo.lpFile = _T(filePath); //文件名
ShExecInfo.lpParameters = _T("123456 HelloWorld!");
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
printf("shell execute exe.\n");
ShellExecuteEx(&ShExecInfo);
printf("wait for exe to execute.\n");
WaitForSingleObject(ShExecInfo.hProcess, INFINITE); // 等待进程结束
printf("exe execute finished.\n");
return 0;
}
- 外部程序
// ToolConsole.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
// argv[0]: "ToolConsole.exe"
// argv[1]: int
// argv[2]: 字符串
int main(int argc, char* argv[])
{
if (argc != 3)
{
return 0;
}
int int_value;
char* str_value = argv[2];
sscanf_s(argv[1], "%d", &int_value);
printf("int value = %d \n", int_value);
printf("str value = %s \n", str_value);
getchar();
return 0;
}
-
程序运行