Wednesday, October 21, 2009

Terminating a process

If at any point you wish to terminate a/your process instantly then you should take a look at TerminateProcess function in Windows SDK(Software Developer Kit) help which comes with Delphi.
TerminateProcess function is defined as
BOOL TerminateProcess(
    HANDLE hProcess, // handle to the process 
    UINT uExitCode  // exit code for the process  
Parameters information according to Delphi Help
  Identifies the process to terminate.
  Windows NT: The handle must have PROCESS_TERMINATE access. For more information, see Process Objects(in Windows SDK Help).

  Specifies the exit code for the process and for all threads terminated as a result of this call. Use the GetExitCodeProcess function to retrieve the process's exit value. Use the GetExitCodeThread function to retrieve a thread's exit value.
Create a new VCL application, add a button, double-click that button and copy-paste
procedure TForm1.Button1Click(Sender: TObject);
  TerminateProcess(GetCurrentProcess, 0);
Your application should terminate instantly.


  1. Hi, I am trying to close a process that i have created etc. Notepad or mspaint. I have tried "TerminateProcess(GetCurrentProcess,0)" but it only closes the button that i have created. Can you advise me how can i close other application like Notepad or mspaint? Thank you!

  2. @CFrental I do NOT understand exactly what you mean by a process you have created, did you use CreateProcess or did you start a mspaint/notepad/etc. instance using WinExec or ShellExecute -- please clarify.
    If you wish to terminate a process you can do it by using TerminateProcess function, GetCurrentProcess is a Windows function which retrieves the process handle of YOUR application(process), therefore it is not needed.
    A simple way to terminate it(if you know the caption) is by using
    TerminateProcess(FindWindow(nil, 'Untitled - Notepad'), 0);
    TerminateProcess(FindWindow(nil, 'untitled - Paint'), 0);
    but it requires you to know the the exact window caption.
    Let me know if this helps, if not, please provide more info on how you create(start) a application.

  3. Hi Dorin Duminica, i launched a notepad/print from the 'start' button on windows. However i would like to terminate the application by using TerminateProcess.

    I tried using the code TerminateProcess(FindWindow(nil, 'Untitled - Notepad'), 0); but it doesn't close the application. I am using delphi 7.

  4. This comment has been removed by the author.

  5. @CFrental sorry for the big delay, I was having trouble with my Internet connection, the freaking modem needed to be replaced.
    I wrote a class which will retrieve a list of all processes running on the system, this list can also terminate a process by name, for example TerminateProcess('notepad.exe')


Blogroll(General programming and Delphi feeds)