Search code examples
windowssecuritywinapigdihandle

Is HWND unique among a window station?


Assume I created two desktops D1 and D2 in WinSta0, and D2 has a window B.

My question is:

Can a thread belonging to D1 get window B's caption text through GetWindowText(hwnd for B, ....)?


Solution

  • The hierarchy is Session => Window Station => Desktop => Thread => window. The session is important when you work with a service, they run in the isolated session 0. Every session has at least the WinSta0 as the interactive window station. Session 0 has additional ones for services.

    A window station has multiple desktops, at least the default desktop that you normally interact with and the Winlogon desktop, a secure one that's used for login and screen savers. Plus additional ones that you create, like your D2 desktop.

    A desktop has a single desktop heap where window objects are stored. Every HWND will be unique in that heap. You'll need GetThreadDesktop() to hop back in the hierarchy and go from a known thread back to the desktop on which it creates windows. EnumDesktopWindows() to get the toplevel windows owned by that desktop.

    Getting the thread ID would normally be an obstacle, you'll need to at least know something about the process. From which you can enumerate the threads owned by that process with, say, CreateToolhelp32Snapshot().

    That gets you the desktop handle. But GetWindowText can only work with D1 handles, you'll need to call SetThreadDesktop() to switch to D2.