
05-10-2009, 02:23 PM
|
|
Newcomer
|
|
Join Date: May 2009
Posts: 1
|
|
RegNotifyChangeKeyValue Handle Question
|
Hi,
I'm pretty new to VB, but have been writing a program using VB 2008 Express. I have a section of code using the RegNotifyChangeKeyValue function that I could compile perfectly using VB Studio 2003, but it throws a InvalidCast Exception under VB 2005/2008. The code is:
Code:
Private Function WaitForChange() As Boolean
Dim notifyEvent As New Threading.AutoResetEvent(False)
Dim KeyHandle As IntPtr
Dim KeyToMonitor As RegistryKey
KeyToMonitor = Registry.CurrentUser.OpenSubKey("Software\Microsoft\MediaPlayer\CurrentMetadata", False)
Dim regKeyType As Type = GetType(RegistryKey)
Dim field As System.Reflection.FieldInfo
field = regKeyType.GetField("hkey", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
KeyHandle = CType(field.GetValue(KeyToMonitor), IntPtr)
Dim err As Integer
err = NativeMethods.RegNotifyChangeKeyValue(KeyHandle, _
True, NotifyFilterFlags.REG_NOTIFY_CHANGE_ATTRIBUTES _
Or NotifyFilterFlags.REG_NOTIFY_CHANGE_LAST_SET _
Or NotifyFilterFlags.REG_NOTIFY_CHANGE_NAME _
Or NotifyFilterFlags.REG_NOTIFY_CHANGE_SECURITY, _
notifyEvent.Handle, True)
If err = 0 Then
notifyEvent.WaitOne()
RaiseEvent KeyChanged(CObj(Me), New EventArgs())
Return True
Else
Debug.WriteLine(err)
Return False
End If
End Function
This throws an Invalid Cast exception at KeyHandle = e(field.GetValue(KeyToMonitor) line. As far as I can tell it is because the variable Field is passing the string Microsoft.Win32.SafeHandles.SafeRegistryHandle rather than an integer. Would anyone be able to tell me how to call the handle of the registry key opened in a way compatible with Safe Keys?
Thanks.
|
|