nil, nil, SW_SHOW);
* 用Windows Explorer打開一個文件夾:
ShellExecute(Handle, 'explore', PChar('c:/windows)',
nil, nil, SW_SHOW);
* 運行一個DOS命令并立即返回:
ShellExecute(Handle, 'open', PChar('command.com'),
PChar('/c copy file1.txt file2.txt'), nil, SW_SHOW);
* 運行一個DOS命令并保持DOS窗口打開 ("stay in DOS"):
ShellExecute(Handle, 'open', PChar('command.com'),
PChar('/k dir'), nil, SW_SHOW);
啟動一個外部程序并不難吧?不過,我們如何知道它是否運行結束了呢?我們的程序又怎樣等待它結束呢?
三、啟動外部程序并等待它結束的函數
我們可以通過進程句柄(process handle)來查看進程(程序)是否結束。為了得到進程句柄,有兩個Win32 API函數可以利用:ShellExecuteEx 或者CreateProces。解決這個問題最簡單的方法是,使用ShellExecuteEx啟動一個外部程序,然后使用WaitForSingleObject管理這個外部程序的進程句柄。我們可以這樣定義一個函數:
……
{ ExecAppWait:功能:運行外部程序并等待它結束。。
運行外部程序APPNAME,參數PARAMS;
Returns:如果外部程序出錯返回 FASLE
}
function ExecAppWait(AppName, Params: string): Boolean ;
……
function ExecAppWait(AppName, Params: string): Boolean;
var
// Structure containing and receiving info about
application to start
ShellExInfo: TShellExecuteInfo;
begin
FillChar(ShellExInfo, SizeOf(ShellExInfo), 0);
with ShellExInfo do begin
cbSize := SizeOf(ShellExInfo);
fMask := see_Mask_NoCloseProcess;
Wnd := Application.Handle;
lpFile := PChar(AppName);
lpParameters := PChar(Params);
nShow := sw_ShowNormal;
end;
Result := ShellExecuteEx(@ShellExInfo);
if Result then
while WaitForSingleObject(ShellExInfo.HProcess, 100) = WAIT_TIMEOUT do
begin
Application.ProcessMessages;
if Application.Terminated then Break;
end;
end;
……
不難理解吧?
建立一個Unit ExecWait,把上面的代碼輸進去。
四、例子
如圖建立Form,源程序如下:
unit DemoUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, SHELLAPI;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
BtnExec: TButton;
CheckBoxWait: TCheckBox;
Label3: TLabel;
Label4: TLabel;
Edit3: TEdit;
Edit4: TEdit;
Label5: TLabel;
procedure BtnExecClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
execwait;
{$R *.DFM}
procedure TForm1.BtnExecClick(Sender: TObject);
var
Success: Boolean;
InstanceID: THandle;
begin
{ 最小化窗口,提醒發生的變化 }
Application.Minimize;
Success := False;
try
if CheckBoxWait.Checked then
Success := ExecAppWait(Edit1.Text, Edit2.Text)
else begin
InstanceID := ShellExecute(Handle, 'open', PChar(Edit1.Text),
PChar(Edit2.Text), nil, SW_SHOW);
Success := InstanceID >= 32; // 小于32可就錯了
end;
finally
// 可別忘了恢復我們的程序的窗口!
Application.Restore;
if not Success then
ShowMessage('Application 1 failed: ' + Edit1.Text + ' ' + Edit2.Text);
end;
try
if CheckBoxWait.Checked then
Success := ExecAppWait(Edit3.Text, Edit4.Text)
else begin
InstanceID := ShellExecute(Handle, 'open', PChar(Edit3.Text),
PChar(Edit4.Text), nil, SW_SHOW);
Success := InstanceID >= 32; //小于32可就錯了
end;
finally
//恢復我們的程序的窗口
Application.Restore;
if not Success then
ShowMessage('Application 2 failed: ' + Edit3.Text + ' ' + Edit4.Text);
end;
end;
end.
OK,沒有問題吧?你趕快試試吧,把它應用到你的程序里。#