c++ - 在没有 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(); 是因为我想学习是否有其他方法可以做到这一点。请帮忙!
解决方案
我建议你使用CreateProcess
功能:
创建一个新进程及其主线程。新进程在调用进程的安全上下文中运行。
您可以设置dwCreationFlags
为CREATE_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);
}
推荐阅读
- swift - 在关联类型对象上使用 KeyPaths
- javascript - 在此示例中,如何将数组对象与正则表达式匹配?
- azure-web-app-service - 无法使用 MSI 实现对 azure 存储容器 (blob) 的 azure Web 应用服务访问
- mininet - Iperf 客户端在使用 TCLinks 的 Mininet 中报告吞吐量过高
- android - 如何通过将键设置为字符串来使用recyclerview-selection?
- java - 在 JTable 中添加 JSpinner 时出现非法参数异常
- node.js - express-session - 会话 id 和 connect.sid 之间的区别?
- c - 为什么我的 AVL 平衡函数会丢失数据?
- docker - ASP.NET Core Docker 容器应用程序无法访问
- html - 如何更好地处理 HTML 标签之间的正则表达式捕获组?