코딩하는 나귀

[출처 : http://delphi.borlandforum.com/impboard/impboard.dll?action=read&db=del_tip&no=148 - 임프(박지훈) 님 글]
 
  1. procedure TForm1.Button1Click(Sender: TObject);   
  2. var   
  3.   start: TStartupInfo;   
  4.   sec: TSecurityAttributes;   
  5.   pinfo: TProcessInformation;   
  6.   hwrite, hread: THandle;   
  7.   BytesRead: DWORD;   
  8.   Buffer: array[0..512of char;   
  9.   ResultString: string;   
  10. begin   
  11.   sec.nLength := sizeof(sec);   
  12.   sec.lpSecurityDescriptor := nil;   
  13.   sec.bInheritHandle := true;   
  14.   
  15.   // 어노니머스 파이프 생성   
  16.   if CreatePipe(hread, hwrite, @sec, 0)<>true then   
  17.   begin   
  18.     ShowMessage('Fail to open pipe.');   
  19.     exit;   
  20.   end;   
  21.   
  22.   // 콘솔어플리케이션 프로세스 실행을 위한 준비   
  23.   FillChar(start, sizeof(STARTUPINFO), 0);   
  24.   start.cb := sizeof(start);   
  25.   start.dwFlags := STARTF_USESTDHANDLES;   
  26.   start.hStdOutput := hwrite;  // 표준출력(stdout) 리다이렉션   
  27.   start.hStdError := hwrite;   // 표준에러(stderr) 리다이렉션   
  28.   
  29.   // 콘솔어플리케이션 프로세스 실행   
  30.   if CreateProcess(nil'dcc32.exe'nilniltrue, DETACHED_PROCESS, nilnil, start, pinfo) <> true then   
  31.   begin   
  32.     ShowMessage(AnsiString('CreateProcess() failed: ') + IntToStr(GetLastError));   
  33.     exit;   
  34.   end;   
  35.   
  36.   CloseHandle(hwrite);//이것을 하지 않으면 프로세스가 block된다   
  37.   
  38.   while ReadFile(hread, Buffer, Length(buffer)-1, BytesRead, niland (BytesRead>0do   
  39.   begin   
  40.     Buffer[BytesRead] := #0;   
  41.     ResultString := ResultString + Buffer;   
  42.     {if GetAsyncKeyState(VK_ESCAPE)<0 then // 실행에 많은 시간이 걸릴 경우  
  43.     begin                                  // 주석해제 필요  
  44.       ShowMessage('Canceled.');  
  45.       break;  
  46.     end;  
  47.     Application.ProcessMessages;}   
  48.   end;   
  49.   CloseHandle(hread);   
  50.   
  51.   Memo1.Lines.Text := ResultString;   
  52. end;