等待外部应用程序的执行结果

在日常程序设计中,有时候需要调用外部应用程序,并且要根据外部应用程序的执行情况来更新本应用程序的当前显示结果。调用外部应用程序的API函数有WinExec()、ShellExecute()、ShellExecuteEx()。但是,如何让应用程序使用ShellExecuteEx() 之类的函数调用外部应用程序后,等待外部应用程序运行结束,之后再执行后续语句呢?

    思路:创建一个线程,在此线程里用ShellExecuteEx() 调用外部程序,调用后阻塞本线程,等待外部程序运行结束。
uses
  ShellAPI; //后面要用到的ShellExecuteInfo结构包含在此单元中, 因此须事先声明之

Type
  TOpenFile = Class(TThread)
    Filename : string;  //完全文件名
    Constructor Create(fName : string);
    Procedure Execute;Override; //线程体
end;

Constructor TOpenFile.Create(fName : string);
begin
  inherited Create(true);
  Filename := fName;
  FreeOnTerminate := true; //自动释放
  Resume;              //恢复运行
end;

Procedure TOpenFile.Execute;
var ShellExInfo : ShellExecuteInfo;
begin
  FillChar(ShellExInfo,SizeOf(ShellExInfo),0);
  with ShellExInfo do    //填充外部命令执行信息
  begin
    cbSize := SizeOf(ShellExInfo);
    fMask := See_Mask_NoCloseProcess;
    Wnd := 0;
    lpFile := PChar(FileName);
    nShow := SW_ShowNormal;
  end;
  ShellExecuteEx(@ShellExInfo);
  WaitForSingleObject(ShellExInfo.hProcess,INFINITE);//阻塞等待进程结束
  Form1.Button2.Click;  //这里写入外部调用的进程执行结束后要做的事情
end;

调用方式:
procedure TForm1.Button1Click(Sender: TObject);
begin
//  if WinExec('c:\windows\regedit.exe',0) > 0 then //成功调用
//    if WinExec()函数执行完毕 then //并且调用返回时
//      Button2.Click;
//以上的功能由下句代替!
  TOpenFile.Create('c:\windows\regedit.exe');
end;
   此代码在大富翁论坛刘麻子的指导下实现。本人本着得之于大富翁,还之于大富的原则,整理并公布于此。

 

谢谢:dawnsoft
方法2:
procedure TForm1.Button1Click(Sender: TObject);
var
  cmdStr:pchar;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
begin
  cmdstr:=pchar('C:\Program Files\WinRAR\Winrar.exe a test.rar "C:\WINDOWS\system32\shell32.dll"');
  {建立进程并等待其结束}
  FillChar(StartupInfo,sizeof(StartupInfo),0);

  CreateProcess(nil,cmdstr,nil,nil,false,0,nil,nil,StartupInfo,ProcessInfo);
  With ProcessInfo do
    begin
      CloseHandle(hThread);
      WaitForSingleObject(hProcess, INFINITE);
      CloseHandle(hProcess);
    end;
  Application.MessageBox('执行完毕!', '提示');

end;

来源:http://www.delphibbs.com/keylife/iblog_show.asp?xid=24550

posted @ 2010-08-25 23:16  覆雨翻云  阅读(1353)  评论(0编辑  收藏  举报