Magician
Magician

Reputation: 25

Locating program positions on screen

If I open notepad.exe from a C++ program using CreateProcess(), is it possible to find the location of that notepad window which has started? I want to find its X and Y positions on screen.

Code: (Improved by suggestions) // Works

    Procces = CreateProcess(
    "C:\\Windows\\System32\\notepad.exe",
    "-l D:\\Testing.txt",
    NULL,
    NULL,
    FALSE,
    0,
    NULL,
    NULL,
    &si,
    &pi);

    WaitForSingleObject(pi.hProcess, 1000);

    HWND hwndNotePad = FindWindow(NULL, "Testing.txt - Notepad");
    RECT r;
    if (INVALID_HANDLE_VALUE != hwndNotePad) {

        GetWindowRect(hwndNotePad, &r);

        cout << r.bottom << endl;
    }

Upvotes: 1

Views: 668

Answers (1)

001
001

Reputation: 13533

Something like this:

HWND hwndNotePad = FindWindow(NULL, "Untitled - Notepad");
RECT r;
if (NULL != hwndNotePad) {
    GetWindowRect(hwndNotePad, &r);
}

If you don't know the exact name, you can use EnumWindows. This is off the top of my head, so there might be errors:

main()
{
    //// .....
    HWND hwndNotePad = NULL;    // Store the result here
    EnumWindows(enumProc, (LPARAM)(&hwndNotePad);  // Check all windows
    if (NULL != hwndNotePad) {
        // Window found
        RECT r;
        GetWindowRect(hwndNotePad, &r);
    }
    //// ......
}

BOOL CALLBACK enumProc(HWND hwnd, LPARAM lParam)
{
    // Get title bar text
    char winTitle[256];
    GetWindowText(hwnd, winTitle, 256);
    if (NULL != strstr(winTitle, "Notepad")) {  // Check for match
        HWND *match = (HWND *)lParam;
        *match = hwnd;                  // Save result
        return FALSE;                   // No need to keep checking
    }
    else {
         return TRUE;          // No match. Keep checking
    }
}

Upvotes: 1

Related Questions