Friday, July 25, 2008

[C] Checking if a Process is active

I've seen lots of questions posted around many forums asking how to check if a process is running. And just to show you how easy it is, here is the code snippit.

#include "tlhelp32.h"
BOOL IsActive( LPCSTR ProcName )
{
HANDLE hProcessSnap; //Handle to store the snapshot in
//Take a snapshot of all running processes
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 );

PROCESSENTRY32 pe32; //Structure for an entry for a process from the snapshot

do
{
if( !strcmp( pe32.szExeFile, ProcName ))
{
return TRUE; //Tells us it is active
}
}while( Process32Next( hProcessSnap, &pe32 )); //Keep searching each process

CloseHandle( hProcessSnap ); //Close current snapshot handle
return 0;
}

See? Not very hard is it! The usage would just be something like:

if( IsActive( "process.exe" ))
{
//code
}

No comments: