C++ 后台运行cmd
#include <string>
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
std::string command = "ping 127.0.0.1";
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
HANDLE hRead, hWrite;
if (!CreatePipe(&hRead, &hWrite, &sa, 0))
{
return 0;
}
STARTUPINFOA si = {sizeof(STARTUPINFO)};
GetStartupInfoA(&si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdError = hWrite;
si.hStdOutput = hWrite;
PROCESS_INFORMATION pi;
if (!CreateProcessA(NULL, (char*)command.c_str(), NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi))
{
return 0;
}
CloseHandle(hWrite);
std::string strRet;
char buff[10] = {0};
DWORD dwRead = 0;
while (ReadFile(hRead, buff, 1, &dwRead, NULL))
{
strRet.append(buff, dwRead);
if(buff[0] == '\r') {
MessageBoxA(0,strRet.c_str(),0,0);
strRet= "";
}
}
CloseHandle(hRead);
return 0;
}
|