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

简介

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. 程序运行


    等待外部程序结束
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 动态调用动态库方法c/c++linuxwindows 关于动态调用动态库方法说明 一、 动态库概述 1、 动态库的...
    KINGZ1993阅读 13,975评论 0 10
  • C语言中内存分配 在任何程序设计环境及语言中,内存管理都十分重要。在目前的计算机系统或嵌入式系统中,内存资源仍然是...
    一生信仰阅读 1,198评论 0 2
  • 基本概念 图像的形状可以看成是图像的轮廓。图像形状的表示方式有:链码、游程码、freeman码等,还有简化方式:B...
    jjkke88阅读 2,283评论 0 0
  • 今生安度 无忧如初
    猪兔子0518阅读 189评论 0 0
  • 我的测试环境配置有4台brick。这次建的卷为dispersed卷(类似raid5) gluster官方建议最佳配...
    高机动老王阅读 1,642评论 0 0