wtuqi
3/16/2020 - 7:08 AM

Registry注册表

//开机启动
Dim Reg As Microsoft.Win32.RegistryKey
Reg = Microsoft.Win32.Registry.CurrentUser
Dim key As Microsoft.Win32.RegistryKey = Reg.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Run", True)
key.SetValue("WindowsCtrl", Application.ExecutablePath) '写入注册表
key.Close()
//创建
Dim newKey As RegistryKey 
newKey = My.Computer.Registry.CurrentUser.CreateSubKey($KeyPath$)
//删除注册表项
Using key As RegistryKey = My.Computer.Registry.LocalMachine.OpenSubKey($SubKey$)
    key.DeleteSubKey($KeyToDelete$)
End Using
Imports Microsoft.Win32'操作注册表程序集需引用((WIN10 HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows))
'示例:Debug.Print(ReadKey("Software\Microsoft\Windows\" & My.Application.Info.AssemblyName, "SN").ToString)
  Public Overridable Function ReadKey(ByVal RegDirectory As String, ByVal RegFile As String) As String '获取注册表值
      Try
          Dim MReg As RegistryKey = Registry.LocalMachine '赋根目录
          Dim Sn As RegistryKey = MReg.OpenSubKey(RegDirectory, True) '示例:("Software\Microsoft\Windows\" & My.Application.Info.AssemblyName, True)
          Return Sn.GetValue(RegFile).ToString
      Catch ex As Exception
          MessageBox.Show(ex.ToString, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
      End Try
  End Function
//读取(从当前用户配置单元中读取字符串注册表值。)
Dim keyValue As String
keyValue = My.Computer.Registry.GetValue($Path$, $Value$, $DefaultValue$)
My.Computer.Registry.SetValue($Path$, $Key$, $Setting$)
//自建
Imports Microsoft.Win32'操作注册表程序集需引用(WIN10 HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows)
 '用法:WriteKey(注册表主目录,文件名,文件值,创建目录(可选)
    
  Public Overridable Function WriteKey(ByVal RegDirectory As String, ByVal RegFile As String, ByVal FileValue As String, Optional ByVal RegCreateDir As String = Nothing) As Boolean
      Try
          If RegCreateDir = Nothing Then
              RegCreateDir = My.Application.Info.AssemblyName
          End If
          Dim MReg As RegistryKey '注意这里是RegistryKey,如果是Registr就会出错
          ''将CPU序列号写入注册表项
          MReg = Registry.LocalMachine '赋根目录
          Dim MDir As RegistryKey = MReg.OpenSubKey(RegDirectory, True) '例("Software\Microsoft\windows", True) '打开目录
          Dim MDir_chlid As RegistryKey = MDir.CreateSubKey(RegCreateDir) '创建目录(以程序集为目录名)
  
  
          MDir_chlid.SetValue(RegFile, FileValue) '示例:("SN", FileValue)
          'F5检查该目录下建立成功
          Return True
      Catch ex As Exception
          MessageBox.Show(ex.ToString, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
          Return False
      End Try
  End Function
//判断该项项是否存在
Dim exists As Boolean = False
Try
    If My.Computer.Registry.CurrentUser.OpenSubKey($keyPath$) IsNot Nothing Then
        exists = True
    End If
Finally
    My.Computer.Registry.CurrentUser.Close()
End Try