建议使用CreateProcess函数来创建,
unit RunAppUnit;
//运行和关闭外部程序单元
//作者:孙占伟
//使用时先引用此单元,然后就可以使用了.
//关闭已经启动的程序的时候使用TerminateApp()
//例子:
//var
//s:TRunApp;
//begin
// s:=TRunApp.Create;
// 使用命令行
// s.CommandLines='/s /m';
// s.RunApp(应用程序路径);
//end;
//关闭程序
//begin
// TerminateApp(s.GetProcessID,5000);//5000指的是关闭程序超时等待的时间
//end;
interface
uses
Windows,Messages;
type
TRunApp=class
private
AppStartInfo:TStartupInfo;
ProcessInfo: TProcessInformation;
CmdLines:string;//命令行
public
constructor Create();
function RunApp(AppName:string):Boolean;//运行的程序路径
function GetProcessID()
WORD;//获取运行的程序的进程ID,用来关闭程序使用
published
property CommandLines:string read CmdLines write CmdLines;
end;
//使用此函数来关闭打开的程序
function TerminateApp(dwPID
WORD;dwTimeOut
WORD)
WORD;stdcall;
implementation
{ TRunApp }
constructor TRunApp.Create;
begin
inherited Create;
FillChar(AppStartInfo, Sizeof(AppStartInfo), #0);
AppStartInfo.cb:=SizeOf(AppStartInfo);
end;
function TerminateAppEnum(TAppHwnd: HWND;
LParam: LPARAM): Boolean;
var
dwID
WORD;
begin
GetWindowThreadProcessId(TAppHwnd,dwID);
if (dwID=DWORD(LParam)) then
begin
PostMessage(TAppHwnd,WM_CLOSE,0,0);
end;
Result :=True;
end;
function TerminateApp(dwPID
WORD;dwTimeOut
WORD)
WORD;
var
hProc:THandle;
dwRet:BOOL;
begin
Result :=0;
hProc:=OpenProcess(SYNCHRONIZE or PROCESS_TERMINATE,False,dwPID);
if (hProc=0) then
begin
Exit;
end;
EnumWindows(@TerminateAppEnum,dwPID);
if (WaitForSingleObject(hProc, dwTimeout)<>WAIT_OBJECT_0) then
begin
dwRet:=TerminateProcess(hProc,0);
if dwRet=True then
Result:=2
else
Result:=0;
end
else
begin
Result:=1;
end;
CloseHandle(hProc);
end;
function TRunApp.GetProcessID: DWORD;
begin
Result:=ProcessInfo.dwProcessId;
end;
function TRunApp.RunApp(AppName: string): Boolean;
begin
Result := CreateProcess(nil,
PChar(AppName+' '+self.CmdLines),
nil, nil,
False,
NORMAL_PRIORITY_CLASS,
nil, nil,
AppStartInfo,
ProcessInfo
);
end;
end.