In
Windows CE: Using ToolHelpAPI to list running processes, I showed how to use the ToolHelpAPI to get a list of running processes or applications. Someone recently asked in one of the newsgroups how to kill an application. The question included code using ToolHelpAPI to find a process, but the code had some problems.
ToolHelpAPI does provide information about the processes, but the function for killing a process, TerminateProcess(), needs a HANDLE to the process. OpenProcess() can be used to get a HANDLE using a Process ID (PID) of the process. The PID is available in the information from ToolHelpAPI.
The following function, KillProcess(), takes a PID as an argument. KillProcess() then gets the HANDLE to the process and terminates the process.
DWORD KillProcess( DWORD PID )
{
HANDLE hApp ;
DWORD ReturnValue = FALSE;
hApp = OpenProcess(PROCESS_TERMINATE, FALSE, PID);
if( hApp )
{
if( !TerminateProcess( hApp, 999 ) )
RETAILMSG( 1, (TEXT("KillApp: Failed to kill app, error %d\n"), GetLastError() ));
else
ReturnValue = TRUE;
}
else
RETAILMSG( 1, (TEXT("KillApp: %X is not currently running\n"), PID ) );
CloseHandle(hApp);
return ReturnValue;
}
The second argument to TerminateProcess() is the exit code. I randomly selected 999 as that value, you could of course use any value that you want to use.
Keep in mind that killing a process with TerminateProcess() is a very harsh way to end a process. This does not allow a process to end gracefully; it just kills the main thread – no main thread, no process. So use this with caution an only if you don’t have a more graceful way to request that the process exit gracefully.
Copyright © 2009 – Bruce Eitman
All Rights Reserved