注册表删除值
本文关键字:删除 注册表 | 更新日期: 2023-09-27 17:53:49
我有一个恼人的问题。我试图使用RegDeleteKey值API删除注册表值(没有我的命名空间),但有一个修改。我希望函数有一个绝对路径作为参数。像这样:
RegDeleteKeyValue("HKEY_CURRENT_USER'Software'Microsoft'Windows'CurrentVersion'Run","myValue")
它看起来像这样(这个可以工作,但是没有绝对路径作为参数,就像它应该的那样):
Private Enum RegHive
HKEY_CLASSES_ROOT = &H80000000
HKEY_CURRENT_USER = &H80000001
HKEY_LOCAL_MACHINE = &H80000002
HKEY_USERS = &H80000003
HKEY_CURRENT_CONFIG = &H80000005
End Enum
RegDeleteKeyValue(Reghive.HKEY_CURRENT_USER,"Software'Microsoft'Windows'CurrentVersion'Run","Myvalue")
我试着像这样修改函数,所以参数只会是绝对路径和注册值。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
DeleteReyKeyValue("HKEY_CURRENT_USER'Software'Microsoft'Windows'CurrentVersion'Run", "123")
End Sub
Public Shared Function DeleteReyKeyValue(ByVal Key As String, ByVal valueName As String) As Long
Dim Handle As IntPtr
Dim Hive As String = Split(Key, "'")(0)
Select Case Hive
Case "HKEY_CLASSES_ROOT"
Handle = CType(&H80000000, IntPtr)
Case "HKEY_CURRENT_USER"
Handle = CType(&H80000001, IntPtr)
Case "HKEY_LOCAL_MACHINE"
Handle = CType(&H80000002, IntPtr)
Case "HKEY_USERS"
Handle = CType(&H80000003, IntPtr)
Case "HKEY_CURRENT_CONFIG"
Handle = CType(&H80000005, IntPtr)
End Select
Key = Key.Replace(Hive, String.Empty)
Return RegDeleteKeyValue(Handle, Key, valueName)
End Function
<DllImport("advapi32.dll")> _
Private Shared Function RegDeleteKeyValue(ByVal handle As IntPtr, ByVal keyName As String, ByVal valueName As String) As Long
End Function
当使用这个,什么都没有发生,没有错误,但注册值没有被删除?阿;为什么呢?
这个问题已经在stackoverflow中得到了回答
所以要删除你的值,你应该使用下面的代码,
string keyName = @"Software'Microsoft'Windows'CurrentVersion'Run";
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
{
if (key == null)
{
// Key doesn't exist. Do whatever you want to handle
// this case
}
else
{
key.DeleteValue("123");
}
}
这将从注册表中删除值。我不知道你为什么要添加这么复杂的代码。下面是msdn的链接:http://social.msdn.microsoft.com/Forums/vstudio/en-US/5b22e94c-37a9-4be5-ad55-3d9229220194/how-to-use-add-read-change-delete-registry-keys-with-vbnet?forum=vbgeneral
它有VB的代码,但仍然与c#几乎相同,您可以使用在线转换器转换代码,http://converter.telerik.com/
感谢您的快速回复。在这种情况下,一个朋友帮我解决了问题,代码现在可以工作了。我只少了一个+"'"现在可以运行了:
Public Shared Function DeleteReyKeyValue(ByVal Key As String, ByVal valueName As String) As Long
Dim Handle As IntPtr
Dim Hive As String = Split(Key, "'")(0)
MsgBox("Hive:" & Hive)
Select Case Hive
Case "HKEY_CLASSES_ROOT"
Handle = CType(&H80000000, IntPtr)
Case "HKEY_CURRENT_USER"
Handle = CType(&H80000001, IntPtr)
Case "HKEY_LOCAL_MACHINE"
Handle = CType(&H80000002, IntPtr)
Case "HKEY_USERS"
Handle = CType(&H80000003, IntPtr)
Case "HKEY_CURRENT_CONFIG"
Handle = CType(&H80000005, IntPtr)
End Select
Key = Key.Replace(Hive + "'", String.Empty)
Return RegDeleteKeyValue(Handle, Key, valueName)
End Function
<DllImport("advapi32.dll")> _
Private Shared Function RegDeleteKeyValue(ByVal handle As IntPtr, ByVal keyName As String, ByVal valueName As String) As Long
End Function
学分:罗津