Tuesday, February 14, 2012

(VB.NET) Remember Application Window Size and Position

This is pretty common, to remember your form’s size and position.  I will use the Application Settings feature to persist the required information, but you could just as easily save it to a text file, .INI file, XML or database.  Whatever floats your app.

We want to remember the size and location of our main window, so we’ll add two settings for that.  We will initialize the settings with negative numbers to signal that they have not been set yet.  In my current case, I also have a splitter bar on the main form, so I’m going to include a setting for it’s size – I’d like the application to remember that also.

Here are the Settings I created.  It doesn’t matter what you call them.  I used WindowLocation, WindowSize and WindowSplitterPosition.


In the Form’s Load event, we’ll call LoadWindowPosition to load and apply the settings:


I have a dual monitor setup with the following Screens (DeviceName, Bounds, WorkingArea)


When we restore our window’s size and position, I’d like to ensure that the top left corner of our form is visible on one of the screens.

Here is a LoadWindowPosition() function to check the screens and abort if the upper left corner isn’t visible on any screen.  You could, if you wanted to, replace the “Bounds” with “WorkingArea”.  See the MSDN Docs for the difference and decide for yourself.


Finally, to make this work, we need to save our settings so they can be loaded the next time the application is run.  I’ll put the code in the FormClosing event of my main window:


Pretty trivial, really!



Agung Sagita Purnama said...

thanks for the knowledge :)

Alvaro Alfaro Santiesteban said...

In this case: Where do the setting go? To the application settings meaning that if I use it on a network the position changes with every user or to the registry meaning every computer has its own setting?

Víctor Sánchez Ramírez said...

Thanks, this is a very useful reference.

Jorge said...

Thank you very much for the post. It works perfectly on Visual Studio 2017 Community Edition.