Vedbex
Vedbex

Reputation: 57

C++ get windows title using process name

edit: how can i get windows title using processname? for example get current title of chrome.exe

Upvotes: 1

Views: 7893

Answers (2)

matheus
matheus

Reputation: 11

Completing the answer of "G.Alexander" and and the comment of Skewjo the get_window_title code is incomplete. So, worked for me, by removing it and calling find_specific_window like below:

wchar_t* caption = new wchar_t[MAX_PATH*2];
HWND h = find_specific_window(processID);
GetWindowTextW(h, caption, MAX_PATH*2);

Upvotes: 0

AleXelton
AleXelton

Reputation: 772

You can get title of specific windows using it's process ID.

If you know the name of executed file(ex: Chrome.exe), you can get Handle with FindWindowEX() or get PID "Chrome.exe" with CreateToolHelp32Snapshot.

Then use EnumWindows to get HWND using HANDLE.

struct param_enum
{
    unsigned long ulPID;
    HWND hWnd_out;
};

HWND find_specific_window(unsigned long process_id)
{
    param_enum param_data;
    param_data.ulPID = process_id;
    param_data.hWnd_out = 0;
    EnumWindows(enum_windows_callback, (LPARAM)&param_data);
    get_window_title(process_id, param_data.hWnd_out);
    return param_data.hWnd_out;
}

BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam)
{
    param_enum& param_data = *(param_enum*)lParam;
    unsigned long process_id = 0;
    GetWindowThreadProcessId(handle, &process_id);
    if (param_data.ulPID != process_id)
    {
        return TRUE;
    }
    param_data.hWnd_out = handle;

    return FALSE;   
}

---------------------------Get Handle---------------------------

HANDLE GetHandleFromProcessPath(TCHAR* szExeName, DWORD& dwPID)
{
    HANDLE hExeName = INVALID_HANDLE_VALUE;
    HANDLE hSnap = INVALID_HANDLE_VALUE;
    PROCESSENTRY32 pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32);

    hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

    if (INVALID_HANDLE_VALUE != hSnap)
    {
        if (Process32First(hSnap, &pe32))
        {
            do 
            {
                //!!! Attention pe32.szExeFile always return exe file name. not window title.
                if (NULL != _tcsstr(pe32.szExeFile, szExeName))
                {
                    hExeName = OpenProcess(PROCESS_ALL_ACCESS, TRUE, pe32.th32ProcessID);
                    dwPID = pe32.th32ProcessID;
                    break;
                }
            } while (Process32Next(hSnap, &pe32));
        }
    }


    return hExeName;
}

Upvotes: 1

Related Questions