WinAPI: How to enumerate processes?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: WinAPI: How to enumerate processes?

  1. #1
    ovidiucucu's Avatar
    ovidiucucu is offline Moderator/Reviewer Power Poster
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,026

    WinAPI: How to enumerate processes?

    Q: How to enumerate currently running processes?

    A: One method is by using Process Status API (PSAPI).

    Example
    Code:
    #include <list>
    #include <iostream>
    #include <Windows.h>
    #include <Psapi.h>
    #pragma comment(lib, "Psapi.lib")
    // Note: linking to Psapi.lib is not necessary if the target system is Windows 7 or newer
    
    DWORD PSAPI_EnumProcesses(std::list<DWORD>& listProcessIDs, DWORD dwMaxProcessCount)
    {
        DWORD dwRet = NO_ERROR;
        listProcessIDs.clear();
        DWORD *pProcessIds = new DWORD[dwMaxProcessCount];
        DWORD cb = dwMaxProcessCount * sizeof(DWORD);
        DWORD dwBytesReturned = 0;
    
        // call PSAPI EnumProcesses
        if (::EnumProcesses(pProcessIds, cb, &dwBytesReturned))
        {
            // push returned process IDs into the output list
            const int nSize = dwBytesReturned / sizeof(DWORD);
            for(int nIndex = 0; nIndex < nSize; nIndex++)
            {
                listProcessIDs.push_back(pProcessIds[nIndex]);
            }
        }
        else
        {
            dwRet = ::GetLastError();
        }
        delete[]pProcessIds;
        return dwRet;
    }
    Code:
    int main()
    {
        std::list<DWORD> listProcessIDs;
        const DWORD dwMaxProcessCount = 1024;
        DWORD dwRet = PSAPI_EnumProcesses(listProcessIDs, dwMaxProcessCount);
        if(NO_ERROR == dwRet)
        {
            const std::list<DWORD>::const_iterator end = listProcessIDs.end();
            std::list<DWORD>::const_iterator iter = listProcessIDs.begin();
            for( ; iter != end; ++iter)
            {
                DWORD dwProcessID = *iter;
                std::cout << "Process ID: " << dwProcessID << std::endl;
                // NOTE: you can pass dwProcessID to ::OpenProcess and further get
                // more process info by using the returned process handle 
            }
        }
        else
        {
            std::cout << "PSAPI_GetProcessesList failed. Error: " << dwRet << std::endl;
            return dwRet;
        }
        return 0;
    }
    Resources and related articles
    Last edited by ovidiucucu; June 8th, 2014 at 09:01 AM.
    Ovidiu Cucu
    "When in Rome, do as Romans do."
    Visit: Microsoft Virtual Academy
    Follow: https://twitter.com/#!/ovidiucucu
    My blog: http://codexpert.ro/blog/author/ovidiu-cucu/

  2. #2
    ovidiucucu's Avatar
    ovidiucucu is offline Moderator/Reviewer Power Poster
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,026

    WinAPI: How to enumerate processes? (2)

    A: Another way is by using Tool Help Library.

    Example
    Code:
    #include <list>
    #include <iostream>
    #include <Windows.h>
    #include <Tlhelp32.h>
    
    DWORD ToolHelp_EnumProcesses(std::list<PROCESSENTRY32>& listProcessInfo)
    {
        DWORD dwRet = NO_ERROR;
        listProcessInfo.clear();
        // take a snapshot of processes
        DWORD dwFlags = TH32CS_SNAPPROCESS;
        HANDLE hSnapshot = ::CreateToolhelp32Snapshot(dwFlags, 0);
        if (INVALID_HANDLE_VALUE == hSnapshot)
        {
            return ::GetLastError();
        }
        PROCESSENTRY32 processEntry = {0};
        processEntry.dwSize = sizeof(PROCESSENTRY32);
        // get info for each process in the snapshot
        if (::Process32First(hSnapshot, &processEntry))
        {
            do
            {
                listProcessInfo.push_back(processEntry);
            } while (::Process32Next(hSnapshot, &processEntry));
        }
        else
        {
            dwRet = ::GetLastError();
        }
        ::CloseHandle(hSnapshot);
        return dwRet;
    }
    Code:
    int main()
    {
        std::list<PROCESSENTRY32> listProcessInfo;
        DWORD dwRet = ToolHelp_EnumProcesses(listProcessInfo);
        if(NO_ERROR == dwRet)
        {
            const std::list<PROCESSENTRY32>::const_iterator end = listProcessInfo.end();
            std::list<PROCESSENTRY32>::const_iterator iter = listProcessInfo.begin();
            for (; iter != end; ++iter)
            {
                const PROCESSENTRY32& processEntry = *iter;
                // NOTE: UNICODE & _UNICODE preprocessor constants are defined in this project
                std::wcout << L"Process ID: " << processEntry.th32ProcessID << std::endl;
                std::wcout << L"Exe file name: " << processEntry.szExeFile << std::endl;
                std::wcout << L"Parent process ID: " << processEntry.th32ParentProcessID << std::endl;
                std::wcout << L"Threads count: " << processEntry.cntThreads << std::endl;
                // ...
            }
        }
        else
        {
            std::cout << "ToolHelp_EnumProcesses falied. Error: " << dwRet << std::endl;
            return dwRet;
        }
    	return 0;
    }
    Resources and related articles
    Last edited by ovidiucucu; June 8th, 2014 at 10:37 AM.
    Ovidiu Cucu
    "When in Rome, do as Romans do."
    Visit: Microsoft Virtual Academy
    Follow: https://twitter.com/#!/ovidiucucu
    My blog: http://codexpert.ro/blog/author/ovidiu-cucu/

  3. #3
    ovidiucucu's Avatar
    ovidiucucu is offline Moderator/Reviewer Power Poster
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,026

    WinAPI: How to enumerate processes? (3)

    A: Also we can use WTSEnumerateProcesses or WTSEnumerateProcessesEx from Remote Desktop Services API (formerly known as Windows Terminal Services API).

    Example
    Code:
    #include <iostream>
    #include <list>
    #include <string>
    #include <Windows.h>
    // Windows Terminal Server API header & lib 
    #include <Wtsapi32.h>
    #pragma comment(lib, "Wtsapi32.lib")
    
    class CProcessInfo
    {
        DWORD m_dwProcessId;
        DWORD m_dwSessionId;
        std::wstring m_strProcessName;
    public:
        CProcessInfo(WTS_PROCESS_INFO& processInfo)
            : m_dwProcessId(processInfo.ProcessId),
            m_dwSessionId(processInfo.SessionId),
            m_strProcessName(processInfo.pProcessName)
        {
        }
        DWORD GetProcessId() const {return m_dwProcessId;}
        DWORD GetSessionId() const {return m_dwSessionId;}
        std::wstring GetProcessName() const {return m_strProcessName;}
    };
    Code:
    DWORD RDSAPI_EnumProcesses(std::list<CProcessInfo>& listProcessInfo)
    {
        listProcessInfo.clear(); // clear output array
        HANDLE hServer = WTS_CURRENT_SERVER_HANDLE; // local machine processes
        PWTS_PROCESS_INFO pProcessInfo = NULL;
        DWORD dwCount = 0;
        // enumerate processes
        if (!::WTSEnumerateProcesses(hServer, 0, 1, &pProcessInfo, &dwCount))
        {
            return ::GetLastError();
        }
        // push processes info into the output list
        for (DWORD dwIndex = 0; dwIndex < dwCount; dwIndex++)
        {
            CProcessInfo processInfo(pProcessInfo[dwIndex]);
            listProcessInfo.push_back(processInfo);
        }
        // free the memory allocated in WTSEnumerateProcesses
        ::WTSFreeMemory(pProcessInfo);
        return NO_ERROR;
    }
    Code:
    int main()
    {
        std::list<CProcessInfo> listProcessInfo;
        DWORD dwRet = RDSAPI_EnumProcesses(listProcessInfo);
        if (NO_ERROR == dwRet)
        {
            const std::list<CProcessInfo>::const_iterator end = listProcessInfo.end();
            std::list<CProcessInfo>::const_iterator iter = listProcessInfo.begin();
            for (; iter != end; ++iter)
            {
                const CProcessInfo& processInfo = *iter;
                std::wcout << L"Process ID: " << processInfo.GetProcessId() << std::endl;
                std::wcout << L"Process name: " << processInfo.GetProcessName() << std::endl;
                std::wcout << L"Session ID: " << processInfo.GetSessionId() << std::endl;
            }
        }
        else
        {
            std::wcout << L"RDSAPI_EnumProcesses failed. Error: " << dwRet << std::endl;
            return dwRet;
        }
        return 0;
    }
    Resources and related articles
    Ovidiu Cucu
    "When in Rome, do as Romans do."
    Visit: Microsoft Virtual Academy
    Follow: https://twitter.com/#!/ovidiucucu
    My blog: http://codexpert.ro/blog/author/ovidiu-cucu/

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center