December 7th, 2011

GetParent, just as confusing as EnumClaw, but it's an actual function!

The function Enum­Claw, documented as returning “the child or the parent of the window”, was a joke, but there’s a function whose behavior is just as confusing as the joke function Enum­Claw: Get­Parent. The Get­Parent function returns the parent window, or owner window, or possibly neither. All that’s left is for it to be a floor wax and it’ll have everything covered. The idea behind Get­Parent is that it returns the parent window. Only child windows have parents, so what happens if you pass something that isn’t a child window? Well, we shouldn’t let a parameter go to waste, right? So let’s have it return the owner window if you pass in a top-level window. But wait, we’re not going to return the owner window for all top-level windows, just for top-level windows which have the WS_POPUP style. This last bit regarding the WS_POPUP style is a leftover from Windows 1.0, where there was a distinction made between “tiled windows” and “popup windows.” Popup windows could overlap, whereas tiled windows could not, and the function was only interested in windows that can overlap. Of course, now that all windows can overlap, the rejection of tiled windows is just a compatibility remnant. Anyway, the algorithm for Get­Parent goes like this:

  • If the window is a child window, then return the parent window.
  • Else, the window is a top-level window. If WS_POPUP style is set, and the window has an owner, then return the owner.
  • Else, return NULL.

Here it is in tabular form, since I’ve discovered that people like tables:

Get­Parent return values WS_CHILD
Set Clear
WS_POPUP Set N/A Owner
Clear Parent NULL

The upper left entry of the table (corresponding to WS_CHILD and WS_POPUP both set) is left as N/A because that combination of styles is illegal.

Fortunately, you don’t have to deal with all the craziness of the Get­Parent function. There are ways to get the parent or owner separately and explicitly without having to deal with Get­Parent‘s quirks.

  • To get the parent window, call GetAncestor(hwnd, GA_PARENT).
  • To get the owner window, call GetWindow(hwnd, GW_OWNER).

Compatibility requirements prevent Get­Parent from ever going away, but that doesn’t mean you are forced to continue using it. Use one of the less confusing alternatives. That’s why they’re there.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.