常用在存系統的參數,而不開放給使用者修改,方便於工程師做為測試或調整使用。
使用Registry必須匯入Win32,一開始先建立登錄檔CreateRegistry(),後就可以依建立的路徑做寫入與讀取。
Imports Microsoft.Win32
Public Class Form1
Private Sub Button_Write_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Write.Click
Write_Registry("Test1", TextBox_RegName.Text, TextBox_RegValue.Text)
End Sub
Public Sub Write_Registry(ByVal sSegment As String, ByVal sRegName As String, ByVal sRegValue As Object)
'把資料寫入註冊區
Dim rRoot As RegistryKey
Dim rReg As RegistryKey
rRoot = Registry.LocalMachine.OpenSubKey("SOFTWARE\KYO", True)
rReg = IIf(sSegment = "", rRoot, rRoot.OpenSubKey(sSegment, True))
rReg.SetValue(sRegName, sRegValue)
rReg.Close()
rRoot.Close()
End Sub
Private Sub CreateRegistry()
Dim rRoot As RegistryKey
rRoot = Registry.LocalMachine.OpenSubKey("SOFTWARE", True)
rRoot = rRoot.CreateSubKey("KYO")
rRoot = rRoot.CreateSubKey("Test1")
rRoot.CreateSubKey("LC")
rRoot.OpenSubKey("LC", True).CreateSubKey("IO")
rRoot.CreateSubKey("Auto")
rRoot.OpenSubKey("Auto", True).CreateSubKey("Valve")
rRoot.OpenSubKey("Auto", True).CreateSubKey("IO")
rRoot.OpenSubKey("Auto", True).CreateSubKey("Speed")
rRoot.CreateSubKey("ColumnOven")
rRoot.Close()
End Sub
Private Sub ReadRegistry()
Dim rRoot As RegistryKey
Dim rLC As RegistryKey
rRoot = Registry.LocalMachine.OpenSubKey("SOFTWARE\KYO\Test1", False)
rLC = rRoot.OpenSubKey("LC")
MsgBox(rLC.GetValue("C1", 1))
End Sub
Private Sub Button_Read_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Read.Click
ReadRegistry()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CreateRegistry()
End Sub
End Class
按Create建立的結果
寫入登錄檔
按Read 讀取LC的C1的值
原始檔下載:WRRegistry.rar