How to get the process name in C++

I guess the OpenProcess function should help, given that your process possesses the necessary rights. Once you obtain a handle to the process, you can use the GetModuleFileNameEx function to obtain full path (path to the .exe file) of the process.

#include "stdafx.h"
#include "windows.h"
#include "tchar.h"
#include "stdio.h"
#include "psapi.h"
// Important: Must include psapi.lib in additional dependencies section
// In VS2005... Project > Project Properties > Configuration Properties > Linker > Input > Additional Dependencies

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE Handle = OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
        FALSE,
        8036 /* This is the PID, you can find one from windows task manager */
    );
    if (Handle) 
    {
        TCHAR Buffer[MAX_PATH];
        if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))
        {
            // At this point, buffer contains the full path to the executable
        }
        else
        {
            // You better call GetLastError() here
        }
        CloseHandle(Handle);
    }
    return 0;
}

Leave a Comment