在Configuration Properties->Linker->System页面的Project Properties中,需要将SubSystem的值设置为Windows (/SUBSYSTEM:WINDOWS)。新控制台应用程序项目的默认值为Console (/SUBSYSTEM:CONSOLE),这会导致 Windows 在启动程序时分配新控制台或附加到父进程的控制台。
您还需要将main 函数更改为WinMain。 `WinMain 的签名是:
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow)
{
// Your code here
}
使用上述方法,子控制台进程仍将创建控制台窗口。由于您在评论中声明要使用popen,因此您不能真正轻松地使用CreateProcess 和SW_HIDE 的正常方式。
您真正想做的是将隐藏的控制台窗口附加到您的进程并允许您的子进程继承它。这可能不是最好的代码,但这里有一种方法:
// Allocates a hidden console window for this process. This console can be
// inherited by child console processes, preventing them from creating a
// visible console. Returns false if the attempt fails.
bool AllocHiddenConsole()
{
TCHAR command[] = _T("cmd.exe");
STARTUPINFO startupInfo{};
PROCESS_INFORMATION processInfo{};
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
if (!CreateProcess(NULL, command, NULL, NULL, FALSE,
CREATE_NEW_CONSOLE, NULL, NULL, &startupInfo, &processInfo))
{
return false;
}
bool attached = false;
for (int i = 0; i < 1000; i++)
{
if (AttachConsole(processInfo.dwProcessId))
{
attached = true;
break;
}
Sleep(10);
}
TerminateProcess(processInfo.hProcess, 0);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
return attached;
}