以不弹黑框的方式运行cmd命令

参考的这里
但是有问题,主要是微软抛弃了一些接口
修改如下

static DWORD RunSilent(char* strFunct, char* strstrParams)
{
    STARTUPINFO StartupInfo;
    PROCESS_INFORMATION ProcessInfo;
    char Args[4096];
    char *pEnvCMD = NULL;
    char *pDefaultCMD = "CMD.EXE";
    ULONG rc;

    memset(&StartupInfo, 0, sizeof(StartupInfo));
    StartupInfo.cb = sizeof(STARTUPINFO);
    StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
    StartupInfo.wShowWindow = SW_HIDE;

    Args[0] = 0;

    //pEnvCMD = getenv("COMSPEC");
    size_t t_requiredSize;
    //errno_t t_err = _dupenv_s(&pEnvCMD,&len,"COMSPEC");
    //获取cmd的路径

    getenv_s(&t_requiredSize, NULL, 0, "COMSPEC");
    if (0 == t_requiredSize)
    {
        printf("robin:not found this comspec\n");
        return -1;
    }
    pEnvCMD = (char *)malloc(t_requiredSize * sizeof(char));
    getenv_s(&t_requiredSize, pEnvCMD, t_requiredSize, "COMSPEC");



    if (pEnvCMD){

        //strcpy(Args, pEnvCMD);
        strcpy_s(Args, pEnvCMD);
    }
    else{
        //strcpy(Args, pDefaultCMD);
        strcpy_s(Args, pDefaultCMD);
    }

    // "/c" option - Do the command then terminate the command window
    //strcat(Args, " /c ");
    strcat_s(Args, " /c ");
    //the application you would like to run from the command window
    //strcat(Args, strFunct);
    //strcat(Args, " ");
    strcat_s(Args, strFunct);
    strcat_s(Args, " ");
    //the parameters passed to the application being run from the command window.
    strcat_s(Args, strstrParams);

    if (!CreateProcess(NULL, Args, NULL, NULL, FALSE,
        CREATE_NEW_CONSOLE,
        NULL,
        NULL,
        &StartupInfo,
        &ProcessInfo))
    {
        return GetLastError();
    }

    WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
    if (!GetExitCodeProcess(ProcessInfo.hProcess, &rc))
        rc = 0;

    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);

    free(pEnvCMD);
    return rc;

}

这些安全的函数没有验证返回值是否正确,我懒~~

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值