I've been using this method so far and it's been working great. You don't have to fiddle around with application settings. Instead, it uses serialization to write a settings file to your working directory. I use JSON, but you can use .NET's native XML serialization or any serialization for that matter.
Put these static methods in a common extensions class. Bonus points if you have a common extensions project that you reference by multiple projects:
const string WINDOW_STATE_FILE = "windowstate.json";
public static void SaveWindowState(Form form)
{
var state = new WindowStateInfo
{
WindowLocation = form.Location,
WindowState = form.WindowState
};
File.WriteAllText(WINDOW_STATE_FILE, JsonConvert.SerializeObject(state));
}
public static void LoadWindowState(Form form)
{
if (!File.Exists(WINDOW_STATE_FILE)) return;
var state = JsonConvert.DeserializeObject<WindowStateInfo>(File.ReadAllText(WINDOW_STATE_FILE));
if (state.WindowState.HasValue) form.WindowState = state.WindowState.Value;
if (state.WindowLocation.HasValue) form.Location = state.WindowLocation.Value;
}
public class WindowStateInfo
{
public FormWindowState? WindowState { get; set; }
public Point? WindowLocation { get; set; }
}
You only need to write that code once and never mess with again. Now for the fun part: Put the below code in your form's Load
and FormClosing
events like so:
private void Form1_Load(object sender, EventArgs e)
{
WinFormsGeneralExtensions.LoadWindowState(this);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
WinFormsGeneralExtensions.SaveWindowState(this);
}
That is all you need to do. The only setup is getting those extensions into a common class. After that, just add two lines of code to your form's code and you're done.
This code will only really work if your WinForm's app has a single form. If it has multiple forms that you want to remember the positions of, you'll need to get creative and do something like this:
public static void SaveWindowState(Form form)
{
var state = new WindowStateInfo
{
WindowLocation = form.Location,
WindowState = form.WindowState
};
File.WriteAllText($"{form.Name} {WINDOW_STATE_FILE}", JsonConvert.SerializeObject(state));
}
I only save location and state, but you can modify this to remember form height and width or anything else. Just make the change once and it will work for any application that calls it.