sergioMoreno
sergioMoreno

Reputation: 354

How to get the process name based on hwnd in C

Programming language: C

Objective: Get the process id and name based on the current hwnd.

Current code:

HWND hwnd;
DWORD process_ID;
PWSTR process_name = NULL;

hwnd = GetForegroundWindow();
process_ID = GetWindowThreadProcessId(hwnd,&process_ID)
process_name = ????

I am not sure if I am passing correctly the arguments to the function GetWindowThreadProcessId. I found on Internet that I could use GetModuleFileNameW to get the process name but I cannot understand the documentation. Please forgive me if it is too easy to solve. I am starting in the world of C. Thanks in advance

Upvotes: 1

Views: 963

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598089

The return value of GetWindowThreadProcessId() is a thread ID, not a process ID, so DO NOT assign that return value to your process_ID variable, or else it will overwrite the value that was output by the lpdwProcessId parameter.

HWND hwnd = GetForegroundWindow();

DWORD process_ID = 0;
if (GetWindowThreadProcessId(hwnd, &process_ID))
{
    // get the process name ...
}
else
{
    // error handling ...
}

Once you have the process ID, you can pass it to OpenProcess() to get a HANDLE to the running process, and then use that HANDLE with either GetModuleFileNameEx(), GetProcessImageFileName() (XP+), or QueryFullProcessImageName() (Vista+) to get the full path and filename of that process's EXE file:

HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_ID);
if (hProcess)
{
    WCHAR process_name[MAX_PATH] = {};
    if (GetModuleFileNameExW(hProcess, NULL, process_name, MAX_PATH))
    {
        // use process_name as needed...
    }
    else
    {
        // error handling ...
    }

    CloseHandle(hProcess);
}
else
{
    // error handling ...
}
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_ID);
if (hProcess)
{
    WCHAR process_name[MAX_PATH] = {};
    if (GetProcessImageFileNameW(hProcess, process_name, MAX_PATH))
    {
        // use process_name as needed...
    }
    else
    {
        // error handling ...
    }

    CloseHandle(hProcess);
}
else
{
    // error handling ...
}
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_ID);
if (hProcess)
{
    WCHAR process_name[MAX_PATH] = {};
    DWORD size = MAX_PATH;
    if (QueryFullProcessImageNameW(hProcess, 0, process_name, &size))
    {
        // use process_name as needed...
    }
    else
    {
        // error handling ...
    }

    CloseHandle(hProcess);
}
else
{
    // error handling ...
}

Upvotes: 4

Related Questions