ShellExecuteEx 没有像我期望的那样工作

ShellExecuteEx not working like I expect it to do

我使用以下功能启动 MS Word 并打开一个文件。这已经完成了,但是 Word 应用程序没有在我的应用程序之上最大化。不能添加到我的函数中吗?

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;

这里有几个问题:

  1. 如果您希望 window 最大化,请传递 SW_MAXIMIZE
  2. 您泄露了进程句柄。处理完进程句柄后调用 CloseHandle
  3. 繁忙的循环有效,但很笨拙。您应该使用等待功能。要么在单独的线程中使用 WaitForSingleObject。或者如果你必须在主线程中等待,并且必须使用 ProcessMessages,请使用 MsgWaitForMultipleObjects