+1  A: 

You may have problems with access rights. In particular on Vista I don't think you can enumerate all processes unless you run with elevated privileges.

You could also try to use the EnumProcesses API. There is a complete example on how to enumerate all processes.

Martin Liversage
+2  A: 

You are using the correct API, namely CreateToolhelp32Snapshot, Process32First and Process32Next. And as you are doing, you should be using the szExeFile member from the struct PROCESSENTRY32.

You are returning from your function when you find a match currently though. Instead you should be incrementing a counter and NOT returning. And return an int with the process count instead of a bool. Also be sure not to do CloseHandle(hSnapshot); until the end of the function after you have the count.

Also make sure to first acquire the privilege SeDebugPrivilege before enumerating, that way you will get all processes across all sessions and users.

To acquire the privilege so you get all sessions:

acquirePrivilegeByName(SE_DEBUG_NAME);// SeDebugPrivilege

Where acquirePrivilegeByName is defined as:

BOOL acquirePrivilegeByName(
          const TCHAR  *szPrivilegeName)
{
    HANDLE   htoken;
    TOKEN_PRIVILEGES tkp;
    DWORD   dwerr;

    //---------------- adjust process token privileges to grant privilege
    if (szPrivilegeName == NULL)
    {
     SetLastError(ERROR_INVALID_PARAMETER);
     return FALSE;
    }

    if (!LookupPrivilegeValue(NULL, szPrivilegeName, &(tkp.Privileges[0].Luid)))
     return FALSE;

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &htoken))
     return FALSE;

    if (!AdjustTokenPrivileges(htoken, FALSE, &tkp, 0, NULL, NULL) ||
     GetLastError() != ERROR_SUCCESS) // may equal ERROR_NOT_ALL_ASSIGNED
    {
     dwerr = GetLastError();
     CloseHandle(htoken);
     SetLastError(dwerr);
     return FALSE;
    }

    CloseHandle(htoken);
    SetLastError(ERROR_SUCCESS);

    return TRUE;
} //acquirePrivilegeByName()
Brian R. Bondy
Thanks! it's as simple as removing the CloseHandle!
djzmo