12,065,316 members (39,923 online)
I wasn't able to find a good example of a generic class for recording the positions of windows. The example code I found typically relies on adding code for each individual window. In my opinion, this has two disadvantages:
The following code is a class that will keep track of one or more windows and record their position when they close. It requires no changes to existing forms, and can handle many forms from just one object.
To instantiate the class, you pass the class an application name to use. This is used to create or open a registry key in the current user hive and it creates a sub key for the forms. Each form has its own sub branch of the forms key which is used to store information about the individual forms.
To handle a form, you call the
HandleForm function. This keeps track of the form in a
hashtable, along with the
formName you pass in. If you want to have the same form opened in two different positions depending on its content or who's calling it, then you can simply pass in different form names, each individual version of the form will now load and save in a different position.
formLocationHandler = new FormManager.FormLocationHandler("Test App"); formLocationHandler.HandleForm("Form2", newForm); newForm.Show();
static function call
HandleFormForApp is also provided as a convenience method if you don't want to bother with the form manager after creating it.
FormManager.FormLocationHandler.HandleFormForApp("Test App", "Form1 Take2", newForm);
When the form closes, the form fires the
form.Closing event, which calls the
FormLocationHandler. This then records the location of the form back into the registry, ready for the next form to be read.
There are a couple of issues with this code, which could be worked around as follows:
form.SizeChangedevents are fired, but this could also wear out your registry and so slow down your application.
hashtablefor a form with the same name (the form name is stored in the
hashtable), and copy the position from the registry.