2014-10-29 53 views
0

我正在C#中開發註冊表監視應用程序以創建註冊表項。我曾嘗試使用p/invoke - 它創建的密鑰,如果它不存在,但如果它確實存在,則它返回錯誤值5 - 訪問被拒絕的錯誤。如何在C#中使用pinvoke regcreatekeyEx監視註冊表項?

enum RegistryDispositionValue : uint 
     { 
      REG_CREATED_NEW_KEY = 0x00000001, 
      REG_OPENED_EXISTING_KEY = 0x00000002 
     } 

    [DllImport("advapi32.dll", SetLastError = true)] 
      private static extern int RegCreateKeyEx(
         IntPtr hKey, 
         string lpSubKey, 
         uint reserved, 
         string lpClass, 
         uint dwOptions, 
         int samDesired, 
         IntPtr lpSecurityAttributes, 
         out IntPtr phkResult, 
         out RegistryDispositionValue lpdwDisposition); 

    int iResult; 
       IntPtr ipKey = IntPtr.Zero; 
       string _registrySubName="SOFTWARE\XYZ\subkey"; 
       RegistryDispositionValue iDisposition; 

       int result = RegCreateKeyEx(HKEY_LOCAL_MACHINE, _registrySubName, 0, null, REG_OPTION_VOLATILE , 0, IntPtr.Zero, out registryKey, out iDisposition); 

AutoResetEvent _eventNotify = new AutoResetEvent(false); 
WaitHandle[] waitHandles = new WaitHandle[] {_eventNotify, _eventTerminate}; 
while (!_eventTerminate.WaitOne(0, true)) 
{ 
result = RegNotifyChangeKeyValue(registryKey, true, _regFilter, _eventNotify.Handle, true); 
if (result != 0) 
    throw new Win32Exception(result); 
if (WaitHandle.WaitAny(waitHandles) == 0) 
{ 
OnRegChanged(); 
} 
} 

我在這裏錯過了什麼?

是否有類似的API(RegNotifyChangeKeyValue()).net內置註冊表類中可用?

+4

.NET的內置註冊表處理有什麼問題? (例如['Microsoft.Win32.RegistryKey'](http://msdn.microsoft.com/en-us/library/microsoft.win32.registrykey%28v=vs.110%29.aspx)。) – Richard 2014-10-29 13:19:45

+3

You don不需要使用ap/invoke層來做到這一點。您可以使用[註冊表](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry(v = vs.110).aspx)類。 – pstrjds 2014-10-29 13:19:53

+2

除非您的程序以[管理員權限]運行,否則無法在HKLM中創建密鑰(http://stackoverflow.com/questions/2818179/how-to-force-my-net-app-to-run-as-administrator-on -windows-7)或者您更改註冊表項的訪問權限。不要使用HKLM,請使用HKCU。 – 2014-10-29 13:47:00

回答