title: C#: How to make a form remember its Bounds and WindowState (Taking dual monitor setups into account)
body: <p>I have made a class which a form can inherit from and it handles form Location, Size and State. And it works nicely. Except for one thing: </p>
  
  <p>When you maximize the application on a different screen than your main one, the location and size (before you maximized) gets stored correctly, but when it is maximized (according to its previous state) it is maximized on my main monitor. When I then restore it to normal state, it goes to the other screen where it was before. When I then maximize it again, it of course maximized on the correct screen.</p>
  
  <p>So my question is... how can I make a form, when it is maximized, remember what screen it was maximized on? And how do I restore that when the form opens again?</p>
  
  <hr>
  
  <h2>Kind of complete solution to problem</h2>
  
  <p>I accepted the answer which had a very good tip about how to if on screen. But that was just part of my problem, so here is my solution:</p>
  
  <p><strong>On load</strong></p>
  
  <ol>
  <li>First get stored <code>Bounds</code> and <code>WindowState</code> from whatever storage.</li>
  <li>Then set the <code>Bounds</code>.</li>
  <li>Make sure <code>Bounds</code> are visible either by <code>Screen.AllScreens.Any(ø =&gt; ø.Bounds.IntersectsWith(Bounds))</code> or <code>MdiParent.Controls.OfType&lt;MdiClient&gt;().First().ClientRectangle.IntersectsWith(Bounds)</code>.
  
  <ul>
  <li>If it doesn't, just do <code>Location = new Point();</code>.</li>
  </ul></li>
  <li>Then set window state.</li>
  </ol>
  
  <p><strong>On closing</strong></p>
  
  <ol>
  <li>Store <code>WindowState</code>.</li>
  <li>If <code>WindowState</code> is <code>FormWindowState.Normal</code>, then store <code>Bounds</code>, otherwise store <code>RestoreBounds</code>.</li>
  </ol>
  
  <p>And thats it! =)</p>
  
  <h2>Some example code</h2>
  
  <p>So, as suggested by <a href="https://stackoverflow.com/users/57488/oliver">Oliver</a>, here is some code. It needs to be fleshed out sort of, but this can be used as a start for whoever wants to:</p>
  
  <h3>PersistentFormHandler</h3>
  
  <p>Takes care of storing and fetching the data somewhere.</p>
  
  <pre><code>public sealed class PersistentFormHandler
  {
      /// &lt;summary&gt;The form identifier in storage.&lt;/summary&gt;
      public string Name { get; private set; }
  
  
      /// &lt;summary&gt;Gets and sets the window state. (int instead of enum so that it can be in a BI layer, and not require a reference to WinForms)&lt;/summary&gt;
      public int WindowState { get; set; }
  
  
      /// &lt;summary&gt;Gets and sets the window bounds. (X, Y, Width and Height)&lt;/summary&gt;
      public Rectangle WindowBounds { get; set; }
  
  
      /// &lt;summary&gt;Dictionary for other values.&lt;/summary&gt;
      private readonly Dictionary&lt;string, Binary&gt; otherValues;
  
  
      /// &lt;summary&gt;
      /// Instantiates new persistent form handler.
      /// &lt;/summary&gt;
      /// &lt;param name="windowType"&gt;The &lt;see cref="Type.FullName"/&gt; will be used as &lt;see cref="Name"/&gt;.&lt;/param&gt;
      /// &lt;param name="defaultWindowState"&gt;Default state of the window.&lt;/param&gt;
      /// &lt;param name="defaultWindowBounds"&gt;Default bounds of the window.&lt;/param&gt;
      public PersistentFormHandler(Type windowType, int defaultWindowState, Rectangle defaultWindowBounds)
          : this(windowType, null, defaultWindowState, defaultWindowBounds) { }
  
      /// &lt;summary&gt;
      /// Instantiates new persistent form handler.
      /// &lt;/summary&gt;
      /// &lt;param name="windowType"&gt;The &lt;see cref="Type.FullName"/&gt; will be used as base &lt;see cref="Name"/&gt;.&lt;/param&gt;
      /// &lt;param name="id"&gt;Use this if you need to separate windows of same type. Will be appended to &lt;see cref="Name"/&gt;.&lt;/param&gt;
      /// &lt;param name="defaultWindowState"&gt;Default state of the window.&lt;/param&gt;
      /// &lt;param name="defaultWindowBounds"&gt;Default bounds of the window.&lt;/param&gt;
      public PersistentFormHandler(Type windowType, string id, int defaultWindowState, Rectangle defaultWindowBounds)
      {
          Name = string.IsNullOrEmpty(id) 
              ? windowType.FullName 
              : windowType.FullName + ":" + id;
  
          WindowState = defaultWindowState;
          WindowBounds = defaultWindowBounds;
  
          otherValues = new Dictionary&lt;string, Binary&gt;();
      }
  
  
      /// &lt;summary&gt;
      /// Looks for previously stored values in database.
      /// &lt;/summary&gt;
      /// &lt;returns&gt;False if no previously stored values were found.&lt;/returns&gt;
      public bool Load()
      {
          // See Note 1
      }
  
      /// &lt;summary&gt;
      /// Stores all values in database
      /// &lt;/summary&gt;
      public void Save()
      {
          // See Note 2
      }
  
      /// &lt;summary&gt;
      /// Adds the given &lt;paramref key="value"/&gt; to the collection of values that will be
      /// stored in database on &lt;see cref="Save"/&gt;.
      /// &lt;/summary&gt;
      /// &lt;typeparam key="T"&gt;Type of object.&lt;/typeparam&gt;
      /// &lt;param name="key"&gt;The key you want to use for this value.&lt;/param&gt;
      /// &lt;param name="value"&gt;The value to store.&lt;/param&gt;
      public void Set&lt;T&gt;(string key, T value)
      {
          // Create memory stream
          using (var s = new MemoryStream())
          {
              // Serialize value into binary form
              var b = new BinaryFormatter();
              b.Serialize(s, value);
  
              // Store in dictionary
              otherValues[key] = new Binary(s.ToArray());
          }
      }
  
      /// &lt;summary&gt;
      /// Same as &lt;see cref="Get{T}(string,T)"/&gt;, but uses default(&lt;typeparamref name="T"/&gt;) as fallback value.
      /// &lt;/summary&gt;
      /// &lt;typeparam name="T"&gt;Type of object&lt;/typeparam&gt;
      /// &lt;param name="key"&gt;The key used on &lt;see cref="Set{T}"/&gt;.&lt;/param&gt;
      /// &lt;returns&gt;The stored object, or the default(&lt;typeparamref name="T"/&gt;) object if something went wrong.&lt;/returns&gt;
      public T Get&lt;T&gt;(string key)
      {
          return Get(key, default(T));
      }
  
      /// &lt;summary&gt;
      /// Gets the value identified by the given &lt;paramref name="key"/&gt;.
      /// &lt;/summary&gt;
      /// &lt;typeparam name="T"&gt;Type of object&lt;/typeparam&gt;
      /// &lt;param name="key"&gt;The key used on &lt;see cref="Set{T}"/&gt;.&lt;/param&gt;
      /// &lt;param name="fallback"&gt;Value to return if the given &lt;paramref name="key"/&gt; could not be found.
      /// In other words, if you haven't used &lt;see cref="Set{T}"/&gt; yet.&lt;/param&gt;
      /// &lt;returns&gt;The stored object, or the &lt;paramref name="fallback"/&gt; object if something went wrong.&lt;/returns&gt;
      public T Get&lt;T&gt;(string key, T fallback)
      {
          // If we have a value with this key
          if (otherValues.ContainsKey(key))
          {
              // Create memory stream and fill with binary version of value
              using (var s = new MemoryStream(otherValues[key].ToArray()))
              {
                  try
                  {
                      // Deserialize, cast and return.
                      var b = new BinaryFormatter();
                      return (T)b.Deserialize(s);
                  }
                  catch (InvalidCastException)
                  {
                      // T is not what it should have been
                      // (Code changed perhaps?)
                  }
                  catch (SerializationException)
                  {
                      // Something went wrong during Deserialization
                  }
              }
          }
  
          // Else return fallback
          return fallback;
      }
  }
  </code></pre>
  
  <p><strong>Note 1:</strong> In the load method you have to look for previously stored <code>WindowState</code>, <code>WindowBounds</code> and other values. We use SQL Server, and have a <code>Window</code> table with columns for <code>Id</code>, <code>Name</code>, <code>MachineName</code> (for <code>Environment.MachineName</code>), <code>UserId</code>, <code>WindowState</code>, <code>X</code>, <code>Y</code>, <code>Height</code>, <code>Width</code>. So for every window, you would have one row with <code>WindowState</code>, <code>X</code>, <code>Y</code>, <code>Height</code> and <code>Width</code> for each user and machine. In addition we have a <code>WindowValues</code> table which just has a foreign key to <code>WindowId</code>, a <code>Key</code> column of type <code>String</code> and a <code>Value</code> column of type <code>Binary</code>. If there is stuff that is not found, I just leave things default and return false.</p>
  
  <p><strong>Note 2:</strong> In the save method you then, of course do the reverse from what you do in the Load method. Creating rows for <code>Window</code> and <code>WindowValues</code> if they don't exist already for the current user and machine.</p>
  
  <h3>PersistentFormBase</h3>
  
  <p>This class uses the previous class and forms a handy base class for other forms.</p>
  
  <pre><code>// Should have been abstract, but that makes the the designer crash at the moment...
  public class PersistentFormBase : Form
  {
      private PersistentFormHandler PersistenceHandler { get; set; }
  
      private bool handlerReady;
  
      protected PersistentFormBase()
      {
          // Prevents designer from crashing
          if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
          {
              Load += persistentFormLoad;
              FormClosing += persistentFormFormClosing;
          }
      }
  
      protected event EventHandler&lt;EventArgs&gt; ValuesLoaded;
      protected event EventHandler&lt;EventArgs&gt; StoringValues;
  
      protected void StoreValue&lt;T&gt;(string key, T value)
      {
          if (!handlerReady)
              throw new InvalidOperationException();
          PersistenceHandler.Set(key, value);
      }
  
      protected T GetValue&lt;T&gt;(string key)
      {
          if (!handlerReady)
              throw new InvalidOperationException();
          return PersistenceHandler.Get&lt;T&gt;(key);
      }
  
      protected T GetValue&lt;T&gt;(string key, T fallback)
      {
          if (!handlerReady)
              throw new InvalidOperationException();
          return PersistenceHandler.Get(key, fallback);
      }
  
      private void persistentFormLoad(object sender, EventArgs e)
      {
          // Create PersistenceHandler and load values from it
          PersistenceHandler = new PersistentFormHandler(GetType(), (int) FormWindowState.Normal, Bounds);
          PersistenceHandler.Load();
          handlerReady = true;
  
          // Set size and location
          Bounds = PersistenceHandler.WindowBounds;
  
          // Check if we have an MdiParent
          if(MdiParent == null)
          {
              // If we don't, make sure we are on screen
              if (!Screen.AllScreens.Any(ø =&gt; ø.Bounds.IntersectsWith(Bounds)))
                  Location = new Point();
          }
          else
          {
              // If we do, make sure we are visible within the MdiClient area
              var c = MdiParent.Controls.OfType&lt;MdiClient&gt;().FirstOrDefault();
              if(c != null &amp;&amp; !c.ClientRectangle.IntersectsWith(Bounds))
                  Location = new Point();
          }
  
          // Set state
          WindowState = Enum.IsDefined(typeof (FormWindowState), PersistenceHandler.WindowState) ? (FormWindowState) PersistenceHandler.WindowState : FormWindowState.Normal;
  
          // Notify that values are loaded and ready for getting.
          var handler = ValuesLoaded;
          if (handler != null)
              handler(this, EventArgs.Empty);
      }
  
      private void persistentFormFormClosing(object sender, FormClosingEventArgs e)
      {
          // Set common things
          PersistenceHandler.WindowState = (int) WindowState;
          PersistenceHandler.WindowBounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds;
  
          // Notify that values will be stored now, so time to store values.
          var handler = StoringValues;
          if (handler != null)
              handler(this, EventArgs.Empty);
  
          // Save values
          PersistenceHandler.Save();
      }
  }
  </code></pre>
  
  <p>And thats pretty much it. To use it, a form would just inherit from the PersistentFormBase. That would automatically take care of bounds and state. If anything else should be stored, like a splitter distance, you would listen for the <code>ValuesLoaded</code> and <code>StoringValues</code> events and in those use the <code>GetValue</code> and <code>StoreValue</code> methods.</p>
  
  <p>Hope this can help someone! Please let me know if it does. And also, please provide some feedback if there is anything you think could be done better or something. I would like to learn =)</p>