Weird behavior saving application location and size
I'm using Windows Forms (C#). I save my window location and size to disk in the Closing
event of my form, using the following properties:
(int) Width, Height -> using the Form.Size property
(int) LocationX, LocationY -> using the Form.Location property
(bool) Maximized -> using the Form.WindowState property
The form is the Application main form. When the application loads, I set those properties to the form. It's simple.
Well, the most of the times it works perfect, but sometimes, only sometimes, the application is shown very little. I have added debug information and these are the values the form returned:
2011-09-01 20:02:44,334 DEBUG 9884 MainFormSettings - Width -> 160
2011-09-01 20:02:44,334 DEBUG 9884 MainFormSettin开发者_开发百科gs - Height -> 27
2011-09-01 20:02:44,334 DEBUG 9884 MainFormSettings - LocationX -> -32000
2011-09-01 20:02:44,334 DEBUG 9884 MainFormSettings - LocationY -> -32000
2011-09-01 20:02:44,334 DEBUG 9884 MainFormSettings - Maximized -> False
I'm sure that my window was not of that size (160, 27) and also the location was not -32000, because I use only one monitor.
This seems that occur when I have the application opened for a long time, but not sure.
- Do you know why sometimes the for has these strange values?
- Could affect store this in the Closing event (I also tried to do it in the Closed event) with the same result?
Thanks in advance
The coordinates you're seeing are due to the fact that the application is minimized when it is closed. Windows "hides" your form by actually moving it from its coordinates to some ridiculously large negative X, Y coordinates.
Verified programmatically. Output from a form app on Vista:
- Current coordinates X: 184 Y: 184
- Default Location Current coordinates X: -32000 Y: -32000
- Minimized Location
From the code:
System.Diagnostics.Debug.WriteLine(
"Current coordinates X: " + Location.X + " Y: " + Location.Y );
To solve this I would simply check for such a value when your app is closing and not actually save it to file. If you don't want to mess with doing math on arbitrary coordinate values you could also check the WindowState.
I found above answer in previous SO post: http://msdn.microsoft.com/en-us/library/system.windows.forms.formwindowstate.aspx
You can use the RestoreBounds property on the form to get the window size + location when the form is minimized.
For example:
private void Form_Closing(object sender, FormClosingEventArgs e)
{
Location locationToSave = this.WindowState == FormWindowState.Minimized ? this.RestoreBounds.Location : this.Location;
Size sizeToSave = this.WindowState == FormWindowState.Minimized ? this.RestoreBounds.Size : this.Size;
WindowState windowStateToSave = this.WindowState;
// ... save your state
}
精彩评论