I have the Process ID and need to close the associate process programatically with Delphi 5
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.
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;
Use EnumWindows() and GetWindowProcessThreadId() to locate all windows that belong to the process, and then send them WM_CLOSE and/or WM_QUIT messages.
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.