Question

I'm using the following code to get a handle of the topmost window:

HWND hwnd;
hwnd = GetForegroundWindow();

The problem with this is that it returns the top most system-wide. Is there any way to get the topmost ONLY from my own application?

I want to get the top most window ONLY of my application. This means, that I need an API to get my own's app top most window and NOT the systemwide top most window as GetForegroundWindow() does. Thanks!

EDIT:

OK, let me be clear here. My problem is that I am able to get the HWND for a window that doesn't belong to MY application. What I want to get is the TOPMOST for ONLY my application. If the HWND belongs to another application then I should not get the information.

Was it helpful?

Solution

Here is a callback you can use with EnumWindows():

BOOL CALLBACK FindTopmostWnd(HWND hwnd, LPARAM lParam)
{
    HWND* pHwnd = (HWND*)lParam;

    HWND myParent = hwnd;
    do
    {
        myParent = GetParent(myParent);
    }
    while (myParent && (myParent != *pHwnd));

    if (myParent != 0)
    {
        // If the window is a menu_worker window then use it's parent
        TCHAR szClassName[7];
        while (0 != GetClassName(hwnd, szClassName, 7)
            && 0 != _tcsncmp(szClassName, TEXT("Dialog"), 6)
            && 0 != _tcsncmp(szClassName, TEXT("Afx"), 3)
            )
        {
            // find the worker's parent
            hwnd = GetParent(hwnd);
        }

        *pHwnd = hwnd;

        return FALSE;
    }

    return TRUE;
}

As Adam points out, the LPARAM passed to EnumWindows() should be a pointer to an HWND. So you probably want to do something like this:

HWND hTopmostWnd = hWnd;
EnumWindows(FindTopmostWnd, (LPARAM)&hTopmostWnd);

OTHER TIPS

Use the GetTopWindow Function, like this:

HWND hwnd;
hwnd = GetTopWindow(NULL);

I don't know that there is a function that does exactly this, but you could probably write one yourself. If your application windows all have a particular window class, then you can use FindWindow or FindWindowEx.

Alternatively, you could use GetForegroundWindow to get the foreground window from all applications and then use GetWindowLong to check the HINSTANCE. If it's not from your application, then keep enumerating the windows by Z-order (using GetWindow) until you find the first one from your application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top