tags:

views:

105

answers:

3

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.

+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
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
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
Assuming the app in question supports such command-line parameters. Most do not.
Remy Lebeau - TeamB
@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
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