saving app size and location

G

Guest

Hi,

I have an app developed using Windows Forms. I need to save the size that
the user resizes the app to, so as to open the app window to that size when
the user restarts the app. I also need to save the desktop location of the
app, so as to display the app window at that location when the app restarts.

What is the best way to do this?

I have implemented this using a config file, such that I save the
size.width, size.height, and location.x, location.y of the app when the event
to close the app is fired. The problem with this is that when the user closes
the app in its minimized state, then the app size is 160 x 30, and the app
re-opens at this size at the next restart.

Thanks.
-Shefali
 
S

Stoitcho Goutsev \(100\) [C# MVP]

Hi shefali,

The problem is that when a window is minimized or maximized the size of the
window in restored state is kept in diferent place. The form class doesn't
expose this info even though it keeps it in a private member of the Form
class.
As far as I can see you have options:
1. Use PInvoke and GetWindowPlacement API to get the size of the restored
window
2. In the Closed event restore first the form. This is has an ugly effect
because of the windows animation.
3. Use reflection to read the private field.
Rectangle GetRestoredRect()
{
Type t = typeof(Form);
FieldInfo fi = t.GetField("restoredWindowBounds", BindingFlags.Instance|
BindingFlags.NonPublic);
return (Rectangle) fi.GetValue(this);
}

Even though the field is of type rectangle only the Size of the restored
bounds is saved.

NOTE: using reflection to read provate fields is wrong and has to be
avoided. It is a big hack that might not work even after the next update or
serivce pack.

4. Keep track of the restored size of the form by your self and use this
size when presisited the form state. This is what I'd recomend if some one
doesn't have any better idea.

HTH
Stoitcho Goutsev (100) [C# MVP]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top