4

When users resize and adjust the location of my program's window (Winforms), they expect to see the window in that same position, even after closing and reopening the program. What I do is store the form's Width, Height, Location.X and Location.Y properties, and set these back when the program is reopened.

The problem is when a window is maximized, Width, Height, X, Y refer not to the non-maximized Width/Height/X/Y, but instead to the Maximized dimensions.

Thus when a user has the window maximized, closes and reopens the program, and the proceeds to un-maximize the window, instead of it returning to the original position/size, it sticks at the full size/position.

So without using a kludge to store variables after certain events execute, how can I obtain the non-maximized position and size when the window is maximized?

Dan W
  • 3,520
  • 7
  • 42
  • 69

1 Answers1

7

The best way to solve this I found is to use the RestoreBounds structure. When a window is maximized, RestoreBounds will refer to the old (non-maximized) size and position. Here is the code to find out these values. Simply save these values upon closing, and then when the program is reopened, you can set the Width, Height, Location.X and Location.Y of the form back to these saved values.

bool b = WindowState == FormWindowState.Maximized;
int xpos = !b? Location.X : RestoreBounds.X;
int ypos = !b? Location.Y : RestoreBounds.Y;
int width = !b? Width : RestoreBounds.Width;
int height = !b? Height : RestoreBounds.Height;
Dan W
  • 3,520
  • 7
  • 42
  • 69
  • 1
    Why on earth would you compare enums by their string representation? Just do a simple `WindowState != FormWindowState.Maximized`. – cremor May 11 '15 at 11:08
  • Further to @cremor's suggestion, you could further improve this answer by testing `WindowState == FormWindowState.Maximized` by assigning that to a var and testing that boolean value instead. – David Arno May 11 '15 at 11:10
  • Okay done. I searched for around 15 minutes to find that RestoreBounds property, so that was the meat of the answer, and it was applied to old code I created, so forgive me that it wasn't 'optimized' to save 5 milliseconds ;) – Dan W May 11 '15 at 13:28