65.9K
CodeProject is changing. Read more.
Home

Change Registry Settings and Broadcast Changes (Refresh Desktop and Windows Explorer)

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Jun 2, 2011

CPOL
viewsIcon

20763

[solved]

Hello all. I found a solution that can change Registry settings and broadcast the changes to the Desktop and Windows Explorer. Here is the code for changing Show/Hide File Extension:

Private Shared Sub HideFilesExtension(ByVal Hide As Boolean)
    Dim root As String = "Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"
    Dim HideFileExt As RegistryKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(root, True)
    HideFileExt.SetValue("HideFileExt", IIf(Hide, 1, 0))
    HideFileExt.Close()
    mhkwins.commons.RefreshExplorer()
End Sub

Here is the code to refresh the Desktop and Window Explorer:

Private Declare Function SHChangeNotify Lib "Shell32.dll" (ByVal wEventID As Int32, _
        ByVal uFlags As Int32, ByVal dwItem1 As Int32, ByVal dwItem2 As Int32) As Int32
  Public Shared Sub RefreshExplorer()
    Call Shell("explorer /select," & "C:\DATA\", AppWinStyle.NormalFocus)
    Threading.Thread.Sleep(3000)
    SHChangeNotify(&H8000000, &H0, 0, 0)
    Dim CLSID_ShellApplication As New Guid("13709620-C279-11CE-A49E-444553540000")
    Dim shellApplicationType As Type = Type.GetTypeFromCLSID(CLSID_ShellApplication, True)
    Dim shellApplication As Object = Activator.CreateInstance(shellApplicationType)
    Dim windows As Object = shellApplicationType.InvokeMember("Windows", _
        System.Reflection.BindingFlags.InvokeMethod, Nothing, shellApplication, New Object() {})
    Dim windowsType As Type = windows.[GetType]()
    Dim count As Object = windowsType.InvokeMember("Count", _
        System.Reflection.BindingFlags.GetProperty, Nothing, windows, Nothing)
    If CInt(count) = 0 Then Exit Sub
    For i As Integer = 0 To CInt(count) - 1
      Dim item As Object = windowsType.InvokeMember("Item", System.Reflection.BindingFlags.InvokeMethod, _
                           Nothing, windows, New Object() {i})
      Dim itemType As Type = item.[GetType]()
      ' only refresh windows explorers       
      Dim itemName As String = DirectCast(itemType.InvokeMember("Name", _
          System.Reflection.BindingFlags.GetProperty, Nothing, item, Nothing), String)
      'MsgBox(itemName)
      If itemName = "Windows Explorer" Then
        itemType.InvokeMember("Refresh", System.Reflection.BindingFlags.InvokeMethod, Nothing, item, Nothing)
      End If
    Next
End Sub

That's all.