Search code examples
delphidelphi-xe5

Hide process window with 'CreateProcess'


I'm using a procedure provided to me that'll run a process but I want the process to be run in the background without the window showing up. The call is

 ExecProcess(ProgPath, '', False);

and the function is

function ExecProcess(ProgramName, WorkDir: string; Wait: boolean): integer;
var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  CreateOK: boolean;
  ExitCode: integer;
  dwExitCode: DWORD;
begin
  ExitCode := -1;

  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);

  if WorkDir <> '' then
  begin
    CreateOK := CreateProcess(nil, Addr(ProgramName[1]), nil, Addr(WorkDir[1]),
      false, CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS, nil, nil,
      StartInfo, ProcInfo);
  end
  else
  begin
    CreateOK := CreateProcess(nil, Addr(ProgramName[1]), nil, nil, false,
      CREATE_NEW_PROCESS_GROUP or NORMAL_PRIORITY_CLASS, nil, Addr(WorkDir[1]),
      StartInfo, ProcInfo);
  end;

  { check to see if successful }

  if CreateOK then
  begin
    // may or may not be needed. Usually wait for child processes
    if Wait then
    begin
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
      GetExitCodeProcess(ProcInfo.hProcess, dwExitCode);
      ExitCode := dwExitCode;
    end;
  end
  else
  begin
    ShowMessage('Unable to run ' + ProgramName);
  end;

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);

  Result := ExitCode;

end;

I have tried to use the StartInfo.wShowWindow attribute with SW_MINIMIZE, SW_FORCEMINIMIZE and SW_SHOWMINIMIZED but it ain't working. I can see that the attribute is changing in the debugger but that's as much as I understand right now. Could someone point out what the problem is?

EDIT: If it matters I'm executing a couple of Fortran modules (.exe) with arguments that'll open up a CMD-window.


Solution

  • Use dwFlags with STARTF_USESHOWWINDOW to forced the usage of wShowWindow

    StartInfo.wShowWindow := SW_HIDE;
    StartInfo.dwFlags := STARTF_USESHOWWINDOW;