Save & Restore Windows App Form Location

Save & Restore the screen size and location of a windows form
The following illustrates how to save & restore the location of a windows application. Net result is that when an application is started, its form is in same location and the same size that it was when it was last closed.\\
Create user properties
Create 2 user properties in the Windows application project.
Property NameTypeScopeValue
WinLocationSystem.Drawing.PointUser0,0
WinSizeSystem.Drawing.SizeUser0,0

Create methods to save and restore window location and size
Save Method
private void SaveSizeAndPosition()  
{    
   // save the form location & size to the property values     
   Properties.Settings.Default.WinLocation = this.Location;     
   Properties.Settings.Default.WinSize = this.Size;       
   save the property settings     
   Properties.Settings.Default.Save();  
}

Restore Method
private void RestorePreviousLocation()  
{     
   do     
   {        
      if (Properties.Settings.Default.WinSize.Width <= 0 || Properties.Settings.Default.WinSize.Height <= 0)        
      {           
         // width / height not set, don't attempt to update the size/location of the window             
         // do the upgrade of the property settings           
         Properties.Settings.Default.Upgrade();             
         // get out now           
         break;        
      }          
	     
      var loc = Properties.Settings.Default.WinLocation;        
      var size = Properties.Settings.Default.WinSize;          
      {           
         // if any part of the saved form location is off the screen, don't restore that size/location. get out now          
         // get the screen size           
         var screenSize = Screen.PrimaryScreen.WorkingArea;     
         if (loc.X < 0) break;           
         if (loc.Y < 0) break;            
         if (loc.X + size.Width > screenSize.Width) break;         
         if (loc.Y + size.Height > screenSize.Height) break;      
      }          
   
      // set the size & location from the property settings       
      this.Location = loc;  // Properties.Settings.Default.WinLocation;      
      this.Size = size;   // Properties.Settings.Default.WinSize;       
   } while (false);  
}

Capture Window Events to Call the Save & Restore Methods
Save the window size & location inside the form closing event trap.
protected override void OnFormClosing(FormClosingEventArgs e)  
{     
   base.OnFormClosing(e);                
   
   // Save the window size & location     
   this.SaveSizeAndPosition();  
}

Restore the window size & location inside the form load event trap.
protected override void OnLoad(EventArgs e)  
{
   base.OnLoad(e);       
	  
   // restore the previously save size & location     
   this.RestorePreviousLocation();  
}


Last modified by Mohit @ 4/14/2025 7:49:56 PM