2008. január 17., csütörtök

How to execute a console application from a Delphi program


Problem/Question/Abstract:

How to execute a console application from a Delphi program

Answer:

This executes a console application, but if your application is not a console, just remove CREATE_NEW_CONSOLE.

function RunApp(const aCmd: string; aWait: boolean; aShowMode: integer): DWORD;
var
  StartUpInfo: TStartUpInfo;
  ProcessInfo: TProcessInformation;
  WaitCode: DWORD;
begin
  Result := 0;
  ZeroMemory(@StartupInfo, SizeOf(TStartupInfo));
  StartUpInfo.cb := SizeOf(StartUpInfo);
  StartUpInfo.wShowWindow := aShowMode;
  StartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
  ZeroMemory(@ProcessInfo, SizeOf(TProcessInformation));
  Win32Check((CreateProcess(nil, PChar(aCmd), nil, nil, False, CREATE_NEW_CONSOLE +
    NORMAL_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo)));
  try
    if aWait then
    begin
      repeat
        WaitCode := WaitForSingleObject(ProcessInfo.hProcess, 10000);
        Win32Check(WaitCode < > WAIT_FAILED);
        if WaitCode = WAIT_TIMEOUT then
        begin
          if MessageDlg('This is a test', mtWarning, [mbYes, mbNo], 0) < > mrYes then
            Break;
        end
        else
          Break;
      until
        False;
      Win32Check(GetExitCodeProcess(ProcessInfo.hProcess, Result));
    end;
  finally
    CloseHandle(ProcessInfo.hThread);
    CloseHandle(ProcessInfo.hProcess);
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése