获取父窗口的正确方法

9 winapi

MSDN说明了以下GetParent功能:

为了获得,而不是使用父窗口,而不是所有者,GetParent使用GetAncestorGA_PARENT标志.

但是当调用GetAncestor(hWnd, GA_PARENT);没有父级的窗口时,它返回桌面窗口,同时GetParent返回NULL.

那么获得父母(而不是所有者)的正确方法是什么,NULL如果没有,那么获得什么?

当然我可以检查是否GetAncestor返回桌面窗口,但这对我来说似乎是一个黑客.

小智 6

这是我想出的:

//
// 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;
}
Run Code Online (Sandbox Code Playgroud)


Rob*_*ens 6

考虑到最新的 Win32 文档,在 2020 年进行了更新:

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);
}
Run Code Online (Sandbox Code Playgroud)