Search code examples
c#wpf.net-7.0

How to explicitely set z-order of windows in WPF app?


I need to set windows in my app in certain order programmatically. I tried to set TopMost on all of them to true in the order I need and then to false, hoping it would override the z-index but the behaviour on the screen is not what it supposed to be:

var windows = Application.Current.Windows.Cast<Window>().ToList();

            foreach (var window in windows)
            {
                window.Topmost = true;
            }

            disp.DelayedAction(() =>
            {
                foreach (var window in windows)
                {
                    if (window is CuteButton) continue;

                    window.Topmost = false;
                }
            },
            500);


Solution

  • You can use SetWindowPos Win32 API to order the windows, e.g.:

    Window window1;
    Window window2;
    ...
    IntPtr firstWindowHandle = ((HwndSource)PresentationSource.FromVisual(window1)).Handle;
    IntPtr secondWindowHandle = ((HwndSource)PresentationSource.FromVisual(window2)).Handle;
    
    const int SWP_NOSIZE = 0x0001;
    const int SWP_NOMOVE = 0x0002;
    SetWindowPos(thisWindowHandle, anotherWindowHandle, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);