给你个例子
void __fastcall Tfrm_Main::RunCMD(AnsiString FullCMD)
{
int FBreak;
Screen->Cursor = crHourGlass;
// If NTdo
security stuff
SECURITY_DESCRIPTOR sd;
SECURITY_ATTRIBUTES sa;
LPSECURITY_ATTRIBUTES lpsa = NULL;
if (IsWindowsNT()) {
InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
SetSecurityDescriptorDacl(&sd, true, NULL, false);
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = &sd;
lpsa = &sa;
}
// Create the Pipe and get r/w handles
HANDLE hReadPipe;
HANDLE hWritePipe;
assert(CreatePipe(&hReadPipe, &hWritePipe, lpsa, 2500000));
// initialize STARTUPINFO struct
STARTUPINFO si;
memset(&si, 0, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW |STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
si.hStdOutput = hWritePipe;
si.hStdError = hWritePipe;
PROCESS_INFORMATION pi;
assert(hWritePipe);
// Run the cmdLine tool
mm
utputs->Lines->Add("Working.....");
Application->ProcessMessages();
if ( CreateProcess(NULL,
FullCMD.c_str(),
NULL,//security
NULL,// security
TRUE,//inherits handles
0,
0,
0,
&si,
&pi)) {
CloseHandle(pi.hThread);
WaitForSingleObject(pi.hProcess, 90000);
// read from the pipe and put in memo
assert(hReadPipe);
DWORD BytesRead;
char dest[4000];
bool RdLoopDone = false;
mm
utputs->Lines->Clear();
FBreak = 1;
if (ExitCode) {
Screen->Cursor = crDefault;
}
while (!RdLoopDone) {
memset(dest, 0, 4000);
assert(ReadFile(hReadPipe, &dest, sizeof(dest), &BytesRead, NULL));
mm
utputs->Lines->Add(String(dest));
if (BytesRead < 4000) RdLoopDone = true;
if (FBreak > 150) RdLoopDone = true;
FBreak++;
}
mm
utputs->Lines->Add("Finished!");
} else
{//if CreateProcess
Screen->Cursor = crDefault;
mm
utputs->Lines->Add("Finished!");
MessageBox(this->Handle, "Unable to execute program./n/nPlease ensure /"sc.exe/" is in program directory!", "Error", MB_OK | MB_ICONERROR);
}
// Process cleanup
CloseHandle(hReadPipe);
CloseHandle(hWritePipe);
CloseHandle(pi.hProcess);
mm
utputs->Perform(EM_SETSEL,0,0);
Screen->Cursor = crDefault;
}