Friday, November 5, 2010

Saving & Loading a Form's state (.NET C#)

Saving and loading the state of a window is a very much appreciated (and often overlooked) feature of an application. There is a slight trick to it though. It is not apparent unless you dig a bit. Based on the state of the Form the Location and Size are not what you expect. If a window is anything but FormWindowState.Normal the Size and Location are not the values you want to save. Instead you need to store the RestoreBounds values of those fields. I have an example implementation below for storing the state of a Form to a string followed by the code to restore it.


   1:  public static string GetFormSettings(Form zForm)
   2:  {
   3:      if (FormWindowState.Normal == zForm.WindowState)
   4:      {
   5:          return zForm.Location.X + ";" + zForm.Location.Y + ";" +
   6:              zForm.Size.Width + ";" + zForm.Size.Height + ";" +
   7:              (int)zForm.WindowState;
   8:      }
   9:      else
  10:      {
  11:          return zForm.RestoreBounds.Location.X + ";" + zForm.RestoreBounds.Location.Y + ";" +
  12:              zForm.RestoreBounds.Size.Width + ";" + zForm.RestoreBounds.Size.Height + ";" +
  13:              (int)zForm.WindowState;
  14:      }
  15:  }
  16:   
  17:  public static void RestoreState(Form zForm, string sInput)
  18:  {
  19:      string[] arraySplit = sInput.Split(new char[] { ';' });
  20:      int[] nValues = new int[5];
  21:      if (5 == arraySplit.Length)
  22:      {
  23:          for (int nIdx = 0; nIdx < arraySplit.Length; nIdx++)
  24:          {
  25:              nValues[nIdx] = int.Parse(arraySplit[nIdx]);
  26:          }
  27:          zForm.Location = new Point(nValues[0], nValues[1]);
  28:          zForm.Size = new Size(nValues[2], nValues[3]);
  29:          zForm.WindowState = (FormWindowState)nValues[4];
  30:      }
  31:  }

MSDN Forms.RestoreBounds

No comments:

Post a Comment