delphi 实现执行外部程序,并等待程序结束的函数


本文整理自网络,侵删。

 type
TExecState = (esNormal, esMinimized, esMaximized, esHidden);

function ExecuteFileWait(Handle: HWND; const FileName, Params, StartDir: string; InitialState: TExecState): Integer;

{
Handle: 传入当前窗口或 Applicaton 的句柄
FileName: 需要传入的文件名
Params: 执行文件所带的参数
StartDir: 执行文件启动路径
InitialState: 窗口显示模式
}

实现代码如下:

{ ExecuteFileWait }

function ExecuteFileWait(Handle: HWND; const FileName, Params, StartDir: string; InitialState: TExecState): Integer;
const
ShowCommands: array[TExecState] of LongInt = (SW_SHOWNORMAL, SW_MINIMIZE, SW_SHOWMAXIMIZED, SW_HIDE);
var
Info: TShellExecuteInfo;
ExitCode: DWORD;
FActive: HWND;
begin
FillChar(Info, SizeOf(Info), 0);
Info.cbSize := SizeOf(TShellExecuteInfo);
with Info do
begin
fMask := SEE_MASK_NOCLOSEPROCESS;
Wnd := Application.MainForm.Handle;
lpFile := PChar(FileName);
lpParameters := PChar(Params);
lpDirectory := PChar(StartDir);
nShow := ShowCommands[InitialState];
end;
FActive := GetActiveWindow;

if ShellExecuteEx(@Info) then
begin
EnableWindow(Handle, False);
repeat
Application.ProcessMessages;
GetExitCodeProcess(Info.hProcess, ExitCode);
until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
EnableWindow(Handle, True);
ShowWindow(Handle, SW_SHOW);
SetActiveWindow(FActive);
SetForegroundWindow(FActive);
Result := ExitCode;
end
else Result := -1;
end;


示范:

begin
ExecuteFileWait(Application.Handle, 'C:\Windows\NotePad.EXE', 'C:\A.txt', '', esMaximized);
ShowMessage('OK! 程序已退出!');
end;

相关阅读 >>

Delphi 保存导出或加载资源文件

Delphi 提升进程权限

Delphi 中相对路径与绝对路径函数说明

Delphi 鼠标拖动控件自由移动位置

Delphi firemonkey的屏幕分辨率hdpi、mdpi、ldpi的差别

Delphi 检测用户超过多长时间没有操作键盘或鼠标

Delphi 守护进程 杀死自己的进程再重新启动自己

Delphi 读取dll所有输出函数名

Delphi百度网盘真实地址解析

Delphi tstylemanager读取vsf皮肤文件信息

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...