Greg Shackles
Greg Shackles

Reputation: 10139

Updating the Z-Order of Many Windows Using Win32 API

The scenario is that I have a list of window handles to top level windows and I want to shift them around so they are arranged in the z-order of my choosing. I started off by iterating the list (with the window I want to end up on top last), calling SetForegroundWindow on each one. This seemed to work some of the time but not always, improving a little when I paused slightly in between each call.

Is there a better way to do this?


Edit:

It looks like the BeginDeferWindowPos/DeferWindowPos/EndDeferWindowPos route is the way to go. However, I can't seem to get it to work with more than one window at a time. When I limit the window list to a single window, it works correctly. When the list has multiple windows, it only seems to get one of them. Here is pseudo code of what I'm doing:

HWND[] windows;
HWND lastWindowHandle = 0;
HDWP positionStructure = BeginDeferWindowPos(windows.length);

for (int i = 0; i < windows.length; i++)
{
    positionStructure = DeferWindowPos(positionStructure, windows[i], 
        lastWindowHandle, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}

EndDeferWindowPos(positionStructure);

I'm sure it's something small/obvious I'm missing here but I'm just not seeing it.

Upvotes: 8

Views: 11502

Answers (2)

Anders
Anders

Reputation: 101756

There is a special set of api's for setting window positions for multiple windows: BeginDeferWindowPos + DeferWindowPos + EndDeferWindowPos (SetWindowPos in a loop will also work of course, but it might have more flicker)

Upvotes: 13

In silico
In silico

Reputation: 52197

You can use SetWindowPos to order your top-level windows.

// Hypothetical function to get an array of handles to top-level windows
// sorted with the window that's supposed to be topmost at the end of array.
HWND* windows = GetTopLevelWindowsInOrder();
int numWindows = GetTopLevelWindowCount();

for(int i = 0; i < numWindows; ++i)
{
    ::SetWindowPos(windows[i], HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
}

Upvotes: 5

Related Questions