Skip to content

Instantly share code, notes, and snippets.

@flipeador
Last active February 10, 2025 00:41
Show Gist options
  • Save flipeador/e97696dfb595aa5d00f2d9203d73ab96 to your computer and use it in GitHub Desktop.
Save flipeador/e97696dfb595aa5d00f2d9203d73ab96 to your computer and use it in GitHub Desktop.
Win32 | GetParent, GetWindow & GetAncestor.
@flipeador
Copy link
Author

GetParentGetWindowGetAncestor

AutoHotkey
#Requires AutoHotkey v2.0

w1 := Gui(, "#1")
w1.Show("w1300 h530")

w2 := Gui("+Parent" . w1.hWnd, "#1.1")
w2.Show("w920 h470")

w3 := Gui("+Parent" . w2.hWnd, "#1.1.1")
w3.Show("w570 h280")

w4 := Gui("+Owner" . w2.hWnd, "#2 #1")
w4.Show("w300 h200")

w5 := Gui("+Owner" . w2.hWnd, "#3 #1.1")
w5.Show("w300 h200")

w6 := Gui("+Owner" . w2.hWnd, "#4 #1.1.1")
w6.Show("w300 h200")

w1.OnEvent("Close", (*) => ExitApp())

for w in [w1, w2, w3, w4, w5, w6] {
    w.SetFont(, "Consolas")
    w.AddText(, "GetParent   : " . GetParent(w.hWnd))
    w.AddText(, "GW_OWNER    : " . GetWindow(w.hWnd, 4))
    w.AddText(, "GA_PARENT   : " . GetAncestor(w.hWnd, 1))
    w.AddText(, "GA_ROOT     : " . GetAncestor(w.hWnd, 2))
    w.AddText(, "GA_ROOTOWNER: " . GetAncestor(w.hWnd, 3))
}

GetParent(hWnd) {
    return FormatHwnd(DllCall("GetParent", "Ptr", hWnd, "Ptr"))
}

GetWindow(hWnd, n) {
    return FormatHwnd(DllCall("GetWindow", "Ptr", hWnd, "Int", n, "Ptr"))
}

GetAncestor(hWnd, n) {
    return FormatHwnd(DllCall("GetAncestor", "Ptr", hWnd, "Int", n, "Ptr"))
}

FormatHwnd(hWnd) {
    hWndDesktop := DllCall("GetDesktopWindow", "Ptr")
    return Format("[{}] {}", hWnd ? WinGetClass(hWnd) : "",
        hWnd ? hWnd == hWndDesktop ? "Desktop" : WinGetTitle(hWnd) : "")
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment