开发者

I have the Process ID and need to close the associate process programmatically with Delphi 5

Can开发者_C百科 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 programmatically 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.


If you want to close a program properly without killing the process:

procedure TmyFRM.btn_closeClick(Sender: TObject);
var
  h: HWND;
begin
  h := FindWindow('Notepad', nil);
  if h <> 0 then
    PostMessage(h, WM_QUIT, 0, 0);
end;

and consider it sometimes you can use WM_Close instead of WM_Quit and you can work around SendMessage instead of PostMessage too. when you are trying to close a program properly without killing its process, so you are following the program routines and programs may respond diffrent to closing messages; for example, some programs will be Minimized to Tray after closing them and etc...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜