首页 > 解决方案 > 在没有 system() 的父窗口中运行外部程序

问题描述

如何在不使用的情况下在父窗口中运行外部程序system()?当前操作系统:Windows 10

我尝试使用

ShellExecute(NULL, "open", target.c_str(), NULL, NULL, SW_SHOW);

但它将在新窗口而不是父窗口中运行。(目标程序是控制台程序。如果程序有 GUI,请改为打开新窗口)我到底想要什么:

system("C:/Users/ELEMENT/source/repos/apath/aprogram.exe arg1 arg2");

但不使用 system();

我不想使用 system(); 是因为我想学习是否有其他方法可以做到这一点。请帮忙!

标签: c++windows

解决方案


我建议你使用CreateProcess功能:

创建一个新进程及其主线程。新进程在调用进程的安全上下文中运行。

您可以设置dwCreationFlagsCREATE_NO_WINDOW阻止进程创建新窗口。

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain(int argc, TCHAR* argv[])
{
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    const LPCSTR program_path = "C:/Users/ELEMENT/source/repos/apath/aprogram.exe";
    const LPCSTR cmdline = " arg1 arg2";

    // Start the child process. 
    if (!CreateProcessA(program_path,   // No module name (use command line)
        const_cast<char*>(cmdline),        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        CREATE_NO_WINDOW,              // The process is a console application that is being run without a console window.
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi)           // Pointer to PROCESS_INFORMATION structure
        )
    {
        printf("CreateProcess failed (%d).\n", GetLastError());
        return;
    }

    // Wait until child process exits.
    WaitForSingleObject(pi.hProcess, INFINITE);

    // Close process and thread handles. 
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
}

推荐阅读