To summarize this example, a folder called "My App" is created under the "VB and VBA Program Settings" folder. A folder called "MySection" is created below the application name. Contained within "MySection" folder, the "MyKey" key holds the actual setting, which in this case is "MySetting".

For a real example, suppose that when users interact with a particular form, they are allowed to move and resize the form as they wish. When they reopen that form, it would be nice to be able to position it in the same place with the same size. This functionality can be implemented with the help of the registry. By storing the values when the form is closed, then the same values can be applied when the form is opened.

The following code is an example of saving the form attributes to the registry:

Private Sub Form_Close()

'Save user form preference to the Windows Registry Database Const cstrAppName As String = "MyApplication" Dim strSectionName As String

'Create a registry section based on the name of the Form strSectionName = Me.Name

'Write Settings to the Windows Registry Database SaveSetting cstrAppName, strSectionName, _

"WindowHeight", Me.WindowHeight SaveSetting cstrAppName, strSectionName, _

"WindowLeft", Me.WindowLeft SaveSetting cstrAppName, strSectionName, _

"WindowTop", Me.WindowTop SaveSetting cstrAppName, strSectionName, _ "WindowWidth", Me.WindowWidth End Sub

In the following code example, a constant variable is created for use throughout the remainder of the procedure. If you prefer to use an application global value, that would work as well. Next, the form name is used to create a Section in the registry. This will facilitate finding the values later in code. Within each Section, the form's Height, Left, Top, and Width are written to the respective keys.

Private Sub Form_Open(Cancel As Integer)

'Reset the window to the saved settings

Const cstrAppName As String

= "MyApplication"

Me.Move _


.Name, "WindowLeft", 1000), _


.Name, "WindowTop", 1000), _


.Name, "WindowWidth", 3 000), _


.Name, "WindowHeight", 3 000)

End Sub

Figure 10-5 displays the result of the registry after the user values are saved.

Igj* Registry Editor



View Favorites Help

S ¡1] V8 and VBA Piograin Settings


Name Data

E _| Micicxott Visual Basic Addlrts

...J NamePaiser


(Default) (value not sei) . JWindowH eight 3G45 .^¡WindowLeft I0G5 [^WindowTop K45 I^WindowWidîh 7350

l" 1 WinZip Computing


1 H

My Conipmer\NKEY_CURRENT_USER\Software\VB and VBA Program Settings\My/

Figure 10-5

Figure 10-5

0 0

Post a comment