Repository navigation
Expand file tree
/
Copy pathLightCore.Process.pas
More file actions
192 lines (151 loc) · 6.43 KB
/
Copy pathLightCore.Process.pas
File metadata and controls
192 lines (151 loc) · 6.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
UNIT LightCore.Process;
{=============================================================================================================
Process Management
2026.09.11
www.GabrielMoraru.com
==============================================================================================================
System functions to query and control running processes:
* ProcessRunning - Check if a process with given name is running
* KillProcess - Terminate all processes matching a given name
Both routines exist only on Windows. Off Windows the unit declares nothing, so a call made in an Android, macOS or iOS build fails to compile instead of returning a wrong Boolean.
Note:
Process.szExeFile from TProcessEntry32 only contains the filename without path,
so we cannot distinguish between processes with the same name running from different locations.
Also see: https://www.experts-exchange.com/questions/20290838/Killing-Exes-running-from-a-delphi-application.html
In this group:
* LightVcl.Common.Shell.pas
* LightVcl.Common.System.pas
* LightVcl.Common.Window.pas
* LightVcl.Common.WindowMetrics.pas
* LightVcl.Common.ExecuteProc.pas
* LightVcl.Common.ExecuteShell.pas
* LightCore.Process.pas
Also see:
https://github.com/HemulGM/TProcessDelphi - TProcess allows one to capture the output from an executable in a cross platform way without using low level API calls and pipes (this is a wrapper around them).
=============================================================================================================}
INTERFACE
{$IFDEF MSWINDOWS}
USES
Winapi.Windows,
System.SysUtils, Winapi.TlHelp32;
function ProcessRunning (CONST ExeFileName: string): Boolean;
function KillProcess (CONST ExeName: string): Boolean;
{$ENDIF}
{ Historical note: GetProcessExeFromHandle and GetProcessExeFromName were considered
but abandoned due to issues. See: https://stackoverflow.com/questions/42637165
The implementations below reference TProcessInfo which is not available. }
IMPLEMENTATION
{$IFDEF MSWINDOWS}
{ Returns True if the specified process is found running.
Parameters:
ExeFileName - Process name to search for. Can be just the filename (e.g., "notepad.exe")
or a full path (e.g., "C:\Windows\notepad.exe"). Only the filename part is used.
Limitation:
Process.szExeFile only contains the filename without path. If multiple processes with the
same name run from different locations, we cannot distinguish between them. }
function ProcessRunning(CONST ExeFileName: string): Boolean;
VAR
SnapshotHandle: THandle;
Process: TProcessEntry32;
TargetExeName: string;
begin
if ExeFileName = ''
then raise Exception.Create('ProcessRunning: ExeFileName parameter cannot be empty');
Result:= FALSE;
{ Extract just the filename - szExeFile never contains path information }
TargetExeName:= ExtractFileName(ExeFileName);
Process.dwSize:= SizeOf(Process);
SnapshotHandle:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if SnapshotHandle = INVALID_HANDLE_VALUE then EXIT;
TRY
if Process32First(SnapshotHandle, Process) then
REPEAT
if SameText(Process.szExeFile, TargetExeName)
then EXIT(TRUE);
UNTIL NOT Process32Next(SnapshotHandle, Process);
FINALLY
CloseHandle(SnapshotHandle);
END;
end;
{ Terminates ALL running processes that match ExeName.
Parameters:
ExeName - Process name to kill (e.g., "notepad.exe"). Must be just the filename, not a path.
Returns:
TRUE - All matching processes were terminated, or no matching processes found.
FALSE - At least one matching process could not be terminated (insufficient rights,
protected process, etc.), or process enumeration failed.
Note:
This function attempts to kill ALL instances of the named process.
Requires PROCESS_TERMINATE right; may fail for elevated/system processes. }
function KillProcess(CONST ExeName: string): Boolean;
VAR
SnapshotHandle: THandle;
ProcEntry: TProcessEntry32;
ProcessHandle: THandle;
begin
if ExeName = ''
then raise Exception.Create('KillProcess: ExeName parameter cannot be empty');
Result:= TRUE;
SnapshotHandle:= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if SnapshotHandle = INVALID_HANDLE_VALUE
then EXIT(FALSE);
TRY
ProcEntry.dwSize:= SizeOf(ProcEntry);
if Process32First(SnapshotHandle, ProcEntry)
then
REPEAT
{ szExeFile only contains filename, but use ExtractFileName for safety }
if SameText(ExtractFileName(ProcEntry.szExeFile), ExeName) then
begin
ProcessHandle:= OpenProcess(PROCESS_TERMINATE, False, ProcEntry.th32ProcessID);
if ProcessHandle <> 0
then
begin
TRY
{ Exit code 0 signals normal termination }
if NOT TerminateProcess(ProcessHandle, 0)
then Result:= FALSE;
{ Continue trying to kill other matching processes even if one fails }
FINALLY
CloseHandle(ProcessHandle);
END;
end
else
Result:= FALSE; { OpenProcess failed - likely insufficient rights }
end;
UNTIL NOT Process32Next(SnapshotHandle, ProcEntry)
else
{ Process32First failed - cannot enumerate processes }
Result:= FALSE;
FINALLY
CloseHandle(SnapshotHandle);
END;
end;
{$ENDIF}
{-------------------------------------------------------------------------------------------------------------
ARCHIVED CODE - Not functional (references undefined types TProcessInfo/TProcessItem)
Kept for historical reference only.
-------------------------------------------------------------------------------------------------------------
function GetProcessExeFromHandle(hWnd: HWND): string;
var
ProcID: DWORD;
ProcessInfo: TProcessInfo;
ProcessItem: TProcessItem;
begin
Result:= '';
GetWindowThreadProcessId(hWnd, @ProcID);
ProcessInfo:= TProcessInfo.Create(nil);
try
ProcessItem:= ProcessInfo.RunningProcesses.FindByID(ProcID);
if Assigned(ProcessItem)
then Result:= ProcessItem.ExeFile;
finally
FreeAndNil(ProcessInfo);
end;
end;
function GetProcessExeFromName(Caption: string): string;
begin
Result:= GetProcessExeFileFromHandle(FindWindow(NIL, Caption));
end;
-------------------------------------------------------------------------------------------------------------}
end.