Go Back  Xtreme Visual Basic Talk > Visual Basic .NET (2002/2003/2005/2008, including Express editions) > .NET File I/O and Registry > RegNotifyChangeKeyValue Handle Question

Thread Tools Display Modes
Old 05-10-2009, 02:23 PM
Irish Irish is offline
Join Date: May 2009
Posts: 1
Default RegNotifyChangeKeyValue Handle Question


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:
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
            RaiseEvent KeyChanged(CObj(Me), New EventArgs())
            Return True
            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?

Reply With Quote

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump


Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..