The site is currently in read-only mode for maintenance. Posting of new items will be available again shortly.
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:
- You have a lot of repeated code in each form.
- Each form is always resized the same. If you want to use the same form for two different purposes, it will always appear in the same place.
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");
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:
- If you open a window, resize it and then open another copy of the window (without shutting the first), it will be same size as the original window, not of the resized window. You could avoid this by saving the form location and size every time the
form.SizeChanged events are fired, but this could also wear out your registry and so slow down your application.
- The other option would be to check through the
hashtable for a form with the same name (the form name is stored in the
hashtable), and copy the position from the registry.
- 2nd November, 2005: Initial post