- 通过在“文件”菜单上单击“新建”,然后单击“项目”,打开一个新的“Windows 应用程序”项目。将出现“新建项目”对话框。
- 从 Visual Basic 项目模板的列表中选择“Windows 应用程序”。将显示新项目。
- 在“项目”菜单中单击“添加类”,将一个新类添加到项目中。将出现“添加新项”对话框。
- 将新模块命名为
StateInfo.vb
,然后单击“打开”。即会显示新类的代码: Public Class StateInfo
End Class
注意可以使用 Visual Studio .NET 代码编辑器,在新类的名称之后键入 Class 关键字,将新类添加到启动窗体中。代码编辑器会提供相应的
End Class语句。
- 若要简化对注册表类的访问,请在包含类语句的源代码顶部添加一条Imports语句:
Imports Microsoft.Win32
- 在Class和End Class语句之间加入以下代码,为类定义三个私有字段:
Private pVal As String ' Holds the LastFile property value.
Private KeyName As String ' Holds the name of the registry key.
Private SubKeyName As String ' Holds the name of the subkey.
这三个字段被声明为Private,只能在类的内部使用。可以通过使用提供更大访问权限的访问修饰符(如Public)来使字段得以从类的外部进行访问。
- 通过添加以下代码为类定义属性:
Public Property LastFile() As String
Get ' Retrieves the property value.
Return pVal
End Get
Set(ByVal Value As String)
pVal = Value
End Set
End Property
- 通过添加以下代码为类定义方法:
Sub SaveStateInfo()
' Save the current value of the LastFile property to the registry.
Dim aKey As RegistryKey
' Create a key if it does not exist.
aKey = Registry.CurrentUser.CreateSubKey(KeyName)
'CreateSubKey(subKey As String)打开一个现有的子项,或者新建一个新子项进行访问,
‘ Registry 提供表示windows注册表中根项的Microsoft.Win32.RegisterKey对象
' Save the property value to the registry.
aKey.SetValue(SubKeyName,pVal)
End Sub
Sub GetStateInfo()
' Restore the property value LastFile from the
' value stored in the registry.
Dim aKey As Object
Dim myRegKey As RegistryKey = Registry.CurrentUser
Try
' This call goes to the Catch block if the registry key is not set.
myRegKey = myRegKey.OpenSubKey(KeyName)
Dim oValue As Object = myRegKey.GetValue(SubKeyName)
pVal = CStr(oValue)
Catch
pVal = "" ' Set to default if key value cannot be read.
End Try
End Sub
- 通过添加名为Sub New的过程为新类定义参数化的构造函数:
Sub New(ByVal RegistryKeyName As String,_
ByVal RegistrySubKeyName As String)
' Save the names of the registry key and subkey in two fields.
KeyName = RegistryKeyName
SubKeyName = RegistrySubKeyName
' Restore the value of the LastFile property from the registry.
MyClass.GetStateInfo()
End Sub
当创建基于此类的对象时,会自动调用Sub New构造函数。此构造函数设置包含注册表项和子项名称的字段的值,并调用一个从注册表中恢复LastFile
属性值的过程。
注意此演练使用注册表来存储类的状态信息。其他应用程序和用户也可以使用存储在注册表中的信息,因此,不应使用注册表来存储安全性信息或重要的应用程序信息。
- 通过添加名为
Finalize
的过程为类定义Finalize析构函数: Protected Overrides Sub Finalize()
' Save the value of the LastFile property to the registry
' when the class loses scope.
SaveStateInfo()
MyBase.Finalize() ' Call Finalize on the base class.
End Sub
在类失去范围后,析构函数Finalize将存储在属性中的值保存到注册表。