Can anyone help me with a coding example to close the associated process when I have the Process ID. I will be using Delphi 5 to perform this operation programatically on a Windows 2003 server.
views:
105answers:
3
+3
A:
Use EnumWindows() and GetWindowProcessThreadId() to locate all windows that belong to the process, and then send them WM_CLOSE and/or WM_QUIT messages.
Remy Lebeau - TeamB
2010-03-31 08:42:11
And if the application doesn't want to close you can force it by calling OpenProcess and TerminateProcess which is the unfriendly, hard way.
Remko
2010-03-31 14:40:01
A:
Along with the WM_CLOSE and WM_QUIT, you can make it really elegant and simply launch a second instance of the app with STOP as the parameter. Like this:
In the project main body...
if ((ParamCount >= 1) and (UpperCase(paramstr(1)) = 'STOP')) then
// send the WM_CLOSE, etc..
When the app launches and sees that it has a parameter of 'STOP', then hunt down the first instance and kill it. Then quit the second instance without creating your main form, etc.. This way, you don't have to have to write/deploy a second program just to kill the first one.
Chris Thornton
2010-03-31 11:19:33
Assuming the app in question supports such command-line parameters. Most do not.
Remy Lebeau - TeamB
2010-04-01 19:15:24
@Remy - yes, this assumes that you can alter the program to accept the STOP parameter, rather than having to write a second program just to shut the first one down.
Chris Thornton
2010-04-01 19:21:53
A:
If you have a process id and want to force that process to terminate, you can use this code:
function TerminateProcessByID(ProcessID: Cardinal): Boolean;
var
hProcess : THandle;
begin
Result := False;
hProcess := OpenProcess(PROCESS_TERMINATE,False,ProcessID);
if hProcess > 0 then
try
Result := Win32Check(Windows.TerminateProcess(hProcess,0));
finally
CloseHandle(hProcess);
end;
end;
vcldeveloper
2010-03-31 16:22:54