The time in Italy is:
Sunday, 1 Aug 2021
You are here: HomeArticlesCheck if an external application is running and count instances of a process

Check if an external application is running and count instances of a process

In this article you can find how check if an external application is running and and count instances of a process. I tested with Visual Studio 6 MFC in Windows 8 (64 bit) and it worked fine.

 You can see a simple example here.

Parameters

sProcName : the name of the process that you want to check if is running or count its instances

Return value

If the function succeeds, it returns an number of instances of a process.
If the function fails, the return value is -1.

int CountProcessInstances(const CString & sProcName, CString & sErr)
{
	HANDLE hProcessSnap;
    PROCESSENTRY32 pe32;
 
    // Take a snapshot of all processes in the system.
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
		return -1;
    }
 
    // Set the size of the structure before using it.
    pe32.dwSize = sizeof(PROCESSENTRY32);
 
    // Retrieve information about the first process,
    // and exit if unsuccessful
    if (!Process32First(hProcessSnap, &pe32))
    {
		CloseHandle(hProcessSnap);          // clean the snapshot object
        return -1;
    }
 
    // Now walk the snapshot of processes, and
    // display information about each process in turn
    int nCount = 0;
    do {
    	if (pe32.szExeFile == sProcName) ++nCount;
    } while (Process32Next(hProcessSnap, &pe32));
 
    CloseHandle(hProcessSnap);
    return nCount;
}

Last modified on Friday, 04 September 2015 14:07

Add comment


Security code
Refresh

Go to top