Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restore a minimized Window in code-behind?

This is somewhat of a mundane question but it seems to me there is no in-built method for it in WPF. There only seems to be the WindowState property which being an enum does not help since i cannot tell whether the Window was in the Normal or Maximized state before being minimized.

When clicking the taskbar icon the window is being restored just as expected, assuming its prior state, but i cannot seem to find any defined method which does that.

So i have been wondering if i am just missing something or if i need to use some custom interaction logic.

(I'll post my current solution as answer)

like image 870
H.B. Avatar asked Apr 03 '11 18:04

H.B.


3 Answers

Not sure this will work for everybody, but I ran into this today and someone on the team suggested "have you tried Normal"?

Turns out he was right. The following seems to nicely restore your window:

if (myWindow.WindowState == WindowState.Minimized)
    myWindow.WindowState = WindowState.Normal;

That works just fine, restoring the window to Maximized if needed. It seems critical to check for the minimized state first as calling WindowState.Normal a second time will "restore" your window to its non-maximized state.

Hope this helps.

like image 126
Eric Liprandi Avatar answered Nov 10 '22 12:11

Eric Liprandi


SystemCommands class has a static method called RestoreWindow that restores the window to previous state.

SystemCommands.RestoreWindow(this); // this being the current window

[Note : SystemCommands class is part of .NET 4.5+ (MSDN Ref) for projects that target to earlier versions of Framework can use the WPF Shell extension (MSDN Ref)]

like image 24
kiran Avatar answered Nov 10 '22 14:11

kiran


WPF's point of view is that this is an OS feature. If you want to mess around with OS features you might have to get your hands dirty. Luckily they have provided us with the tools to do so. Here is a UN-minimize method that takes a WPF window and uses WIN32 to accomplish the effect without recording any state:

public static class Win32
{
    public static void Unminimize(Window window)
    {
        var hwnd = (HwndSource.FromVisual(window) as HwndSource).Handle;
        ShowWindow(hwnd, ShowWindowCommands.Restore);
    }

    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, ShowWindowCommands nCmdShow);

    private enum ShowWindowCommands : int
    {
        /// <summary>
        /// Activates and displays the window. If the window is minimized or 
        /// maximized, the system restores it to its original size and position. 
        /// An application should specify this flag when restoring a minimized window.
        /// </summary>
        Restore = 9,
    }
}
like image 15
Rick Sladkey Avatar answered Nov 10 '22 14:11

Rick Sladkey