Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way of getting the parent window

Tags:

winapi

The MSDN says the following about the GetParent function:

To obtain the parent window and not the owner, instead of using GetParent, use GetAncestor with the GA_PARENT flag.

But when calling GetAncestor(hWnd, GA_PARENT); for a window that doesn't have a parent, it returns the desktop window, while GetParent returns NULL.

So what is the correct way of getting a parent (and not the owner), and getting NULL if there are none?

Of course I could check whether GetAncestor returns the desktop window, but that seems like a hack to me.

like image 678
Ben Avatar asked Jun 01 '13 11:06

Ben


2 Answers

Updated in the year 2020 considering the latest Win32 documentation:

HWND GetRealParent(HWND hWnd)
{
    HWND hWndOwner;

    // To obtain a window's owner window, instead of using GetParent,
    // use GetWindow with the GW_OWNER flag.

    if (NULL != (hWndOwner = GetWindow(hWnd, GW_OWNER)))
        return hWndOwner;

    // Obtain the parent window and not the owner
    return GetAncestor(hWnd, GA_PARENT);
}
like image 56
Robert Stevens Avatar answered Sep 22 '22 09:09

Robert Stevens


Here's what I came up with:

//
// Returns the real parent window
// Same as GetParent(), but doesn't return the owner
//
HWND GetRealParent(HWND hWnd)
{
    HWND hParent;

    hParent = GetAncestor(hWnd, GA_PARENT);
    if(!hParent || hParent == GetDesktopWindow())
        return NULL;

    return hParent;
}
like image 22
Ben Avatar answered Sep 22 '22 09:09

Ben