Obtain non-maximized window position/size when win

2019-07-23 17:28发布

问题:

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?

回答1:

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;