Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Win32 - Getting App Name using PID and Executable Path

I'd like to get the name of an application on Windows. Currently I'm using EnumProcesses() to enumerate all processes and receive a list of PIDs.

Then I'm looping through all PIDs, each iteration looks like this, when aProcess[i] is the current PID:

HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, aProcesses[i]);
std::string processName = get_process_name(proc);

My get_process_name(proc) function uses GetModuleFileNameEx to get the executable path and GetProcessImageFileName in order to retrieve the name of the executable file.

What I want to retrieve is basically the App Name, as it is displayed in the Windows Task Manager.

I've looked throughout Win32 API's documentation and could not find a clue on how to achieve this. I've tried looking for other ways such as Windows Shell tasklist but it outputs different things, for example- Google Chrome:

Image Name: chrome.exe PID: 84 Session Name: Console

I'd really appreciate any thought on the matter, whether it be the Win32 API or some other way I can implement through C++ code.

like image 553
Fizban Avatar asked Oct 22 '25 14:10

Fizban


1 Answers

You can do this with GetFileVersionInfoA and VerQueryValueA.

You just need to follow the example given in the VerQueryValueA document.

Here is my sample:

struct LANGANDCODEPAGE {
WORD wLanguage;
WORD wCodePage;
} *lpTranslate;

int main()
{
    HANDLE handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION , FALSE, 2140);   //Modify pid to the pid of your application
    if (!handle) return 0;
    wchar_t pszFile[MAX_PATH] = L"";
    DWORD len = MAX_PATH;
    QueryFullProcessImageName(handle, 0, pszFile, &len);
    UINT dwBytes, cbTranslate;
    DWORD dwSize = GetFileVersionInfoSize(pszFile, (DWORD*)&dwBytes);
    if (dwSize == 0) return 0;
    LPVOID lpData = (LPVOID)malloc(dwSize);
    ZeroMemory(lpData, dwSize);
    if (GetFileVersionInfo(pszFile, 0, dwSize, lpData))
    {
        VerQueryValue(lpData,
            L"\\VarFileInfo\\Translation",
            (LPVOID*)&lpTranslate,
            &cbTranslate);
        wchar_t strSubBlock[MAX_PATH] = { 0 };
        wchar_t* lpBuffer;

        for (int i = 0; i < (cbTranslate / sizeof(struct LANGANDCODEPAGE)); i++)
        {
            StringCchPrintf(strSubBlock,50,
                L"\\StringFileInfo\\%04x%04x\\FileDescription",
                lpTranslate[i].wLanguage,
                lpTranslate[i].wCodePage);
            VerQueryValue(lpData,
                strSubBlock,
                (void**)&lpBuffer,
                &dwBytes);
            std::wcout << lpBuffer << std::endl;
        }
    }
    if(lpData) free(lpData);
    if (handle) CloseHandle(handle);
    return 0;
}

And it works for me:

enter image description here

like image 134
Zeus Avatar answered Oct 25 '25 03:10

Zeus