Search code examples
delphishellexecute

ShellExecuteEx not working like I expect it to do


I use the folowing function to start MS Word and open a file. This is done OK but the Word app is not maximized on top of my application. Is that not possible to add to my function?

function TFiles.ExecuteAndWait(const aFile: string; aParam: string = ''; const aHidden: boolean = False): integer;
var
  SEInfo: TShellExecuteInfo;
  ExitCode: DWORD;
begin
  FillChar(SEInfo, SizeOf(SEInfo), 0) ;
  SEInfo.cbSize := SizeOf(TShellExecuteInfo) ;
  with SEInfo do
    begin
      fMask := SEE_MASK_NOCLOSEPROCESS;
      Wnd := Application.Handle;
      lpFile := PChar(aFile) ;
      lpParameters := PChar(aParam) ;
      if aHidden = True then
        nShow := SW_HIDE
      else
        nShow := SW_SHOWNORMAL;
    end;
  if ShellExecuteEx(@SEInfo) then
    begin
      repeat
        Application.ProcessMessages;
        GetExitCodeProcess(SEInfo.hProcess, ExitCode) ;
      until (ExitCode <> STILL_ACTIVE) Or Application.Terminated;
      Result := ExitCode;
    end
  else
    Result := -1;
end;

Solution

  • There are a few problems here:

    1. Pass SW_MAXIMIZE if you want the window to be maximized.
    2. You leak the process handle. Call CloseHandle when you have finished with the process handle.
    3. The busy loop works, but is clumsy. You should use a wait function. Either in a separate thread use WaitForSingleObject. Or if you must wait in the main thread, and must use ProcessMessages, use MsgWaitForMultipleObjects.