0
votes

I need handle another running application by name, id, or process handle. I get the ID and Process handles but I don't know how get handle of window to change external program title.

There is my code:

BOOL CFindProcess::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    CComboBox* pComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_PROCESS);
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 proc;
    proc.dwSize = sizeof(PROCESSENTRY32);
    if (Process32First(hSnap, &proc)){
        pComboBox->AddString(proc.szExeFile);
        while (Process32Next(hSnap, &proc)){
            if (0!=wcscmp(proc.szExeFile, L"svchost.exe"))
                pComboBox->AddString(proc.szExeFile);
            if (wcscmp(proc.szExeFile, L"notepad.exe") == 0){
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc.th32ProcessID);
                GetProcessId(hProcess);
                AfxMessageBox(L"Handeled");
                //SetWindowText(hProcess, L"Weather");
                CloseHandle(hProcess);
            }
        }
    }
    CloseHandle(hSnap);
    return TRUE;
}

my question is how get window handle of notepad.exe by name or ID, Process handles with MFC?

1
FindWindow can find by name. EnumWindows with GetWindowProcessId can match a window up with a process ID. - Jerry Coffin
as I know FindWindow searching for titles of processing application, but not for Process name. title and process name can be different right? I don't understand how EnumWindows works can u help me with explanation? - Klasik
Yes, FindWindow only finds by window title and/or class name. To find by process ID, you enumerate windows, then call GetWindowThreadProcessId for each to find a window created by the correct process. - Jerry Coffin

1 Answers

2
votes

This code demonstrates what Jerry is referring to:

struct MYFINDSTRUCT
{
    DWORD dwPID;
    HWND hWnd;
};

BOOL CALLBACK MyWndEnum(HWND hwnd,LPARAM lParam)
{
    MYFINDSTRUCT* pP = (MYFINDSTRUCT*)lParam;
        DWORD dwPID = 0;
    GetWindowThreadProcessId(hwnd,&dwPID);
    if(dwPID==pP->dwPID)
    {
        pP->hWnd = hwnd;
        return 0;
    }
    return 1;
}

HWND GetProcessHWND(unsigned int nPID)
{
    MYFINDSTRUCT p;
    p.hWnd = 0;
    p.dwPID = nPID;
    EnumWindows(MyWndEnum,(LPARAM)&p);
    return p.hWnd;
}