[代码] ShellExecute调用外部程序_VS2017

2018-04-08  本文已影响0人  CrazyTiger

简介

ShellExecute的功能是运行一个外部程序(或者是打开一个已注册的文件、打开一个目录、打印一个文件等等),并对外部程序有一定的控制。有几个API函数都可以实现这些功能,但是在大多数情况下ShellExecute是更多的被使用的,同时它并不是太复杂。

示例

  1. 宿主程序
#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;
}
  1. 外部程序
// 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;
}
  1. 程序运行


    等待外部程序结束
上一篇下一篇

猜你喜欢

热点阅读