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

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

引用ShellAPI单元;

复制代码
 1 type
 2 TExecState = (esNormal, esMinimized, esMaximized, esHidden);
 3 
 4 function ExecuteFileWait(Handle: HWND; const FileName, Params, StartDir: string; InitialState: TExecState): Integer;
 5 
 6 {
 7 Handle: 传入当前窗口或 Applicaton 的句柄
 8 FileName: 需要传入的文件名
 9 Params: 执行文件所带的参数
10 StartDir: 执行文件启动路径
11 InitialState: 窗口显示模式
12 }
13 
14 实现代码如下:
15 
16 { ExecuteFileWait }
17 
18 function ExecuteFileWait(Handle: HWND; const FileName, Params, StartDir: string; InitialState: TExecState): Integer;
19 const
20 ShowCommands: array[TExecState] of LongInt = (SW_SHOWNORMAL, SW_MINIMIZE, SW_SHOWMAXIMIZED, SW_HIDE);
21 var
22 Info: TShellExecuteInfo;
23 ExitCode: DWORD;
24 FActive: HWND;
25 begin
26 FillChar(Info, SizeOf(Info), 0);
27 Info.cbSize := SizeOf(TShellExecuteInfo);
28 with Info do
29 begin
30 fMask := SEE_MASK_NOCLOSEPROCESS;
31 Wnd := Application.MainForm.Handle;
32 lpFile := PChar(FileName);
33 lpParameters := PChar(Params);
34 lpDirectory := PChar(StartDir);
35 nShow := ShowCommands[InitialState];
36 end;
37 FActive := GetActiveWindow;
38 
39 if ShellExecuteEx(@Info) then
40 begin
41 EnableWindow(Handle, False);
42 repeat
43 Application.ProcessMessages;
44 GetExitCodeProcess(Info.hProcess, ExitCode);
45 until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
46 EnableWindow(Handle, True);
47 ShowWindow(Handle, SW_SHOW);
48 SetActiveWindow(FActive);
49 SetForegroundWindow(FActive);
50 Result := ExitCode;
51 end
52 else Result := -1;
53 end;
54 
55 
56 示范:
57 
58 begin
59 ExecuteFileWait(Application.Handle, 'C:\Windows\NotePad.EXE', 'C:\A.txt', '', esMaximized);
60 ShowMessage('OK! 程序已退出!');
61 end;
复制代码

 

posted @   Thenext  阅读(264)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示