要求:視窗隱藏,輸出重新導向到指定的檔案。
// Setting security for output handle (necessary)
SECURITY_ATTRIBUTES sa;
memset(&sa, 0, sizeof(SECURITY_ATTRIBUTES));
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
// Setting output handle
HANDLE hConsoleRedirect = CreateFile((L"out.txt").c_str(), GENERIC_WRITE|GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(hConsoleRedirect == INVALID_HANDLE_VALUE) return;
// Setting console standup info
STARTUPINFO si;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hConsoleRedirect;
si.hStdError = hConsoleRedirect;
// Setting process info
PROCESS_INFORMATION pi;
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
// Excute command
wstring cmd = L"program.exe -argument";
bool bResult = CreateProcess(NULL, (LPWSTR) cmd.c_str(), NULL, NULL, TRUE, CREATE_NEW_CONSOLE|CREATE_UNICODE_ENVIRONMENT, NULL, NULL, &si, &pi);
DWORD ret = WaitForSingleObjectEx(pi.hProcess, INFINITE, FALSE);
// Close handles
CloseHandle(hConsoleRedirect);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);