簡介
ShellExecute的功能是運(yùn)行一個外部程序(或者是打開一個已注冊的文件琐谤、打開一個目錄泡一、打印一個文件等等)田炭,并對外部程序有一定的控制授瘦。有幾個API函數(shù)都可以實(shí)現(xiàn)這些功能近她,但是在大多數(shù)情況下ShellExecute是更多的被使用的叉瘩,同時它并不是太復(fù)雜。
示例
- 宿主程序
#include "stdafx.h"
#include "windows.h "
#include "shellapi.h "
int main()
{
char filePath[MAX_PATH];
GetCurrentDirectory(1000, filePath); //得到當(dāng)前工作路徑
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); // 等待進(jìn)程結(jié)束
printf("exe execute finished.\n");
return 0;
}
- 外部程序
// ToolConsole.cpp: 定義控制臺應(yīng)用程序的入口點(diǎn)粘捎。
//
#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;
}
-
程序運(yùn)行
等待外部程序結(jié)束