C#: Refresh Windows Desktop and Explorer

September 2nd, 2010 by Mel Leave a reply »

This post is mostly for my own reference since the following code is actually found elsewhere online and is not my original work. However the code to both refresh the desktop and any open explorer windows is generally found in parts, so here I’ve combined it for convenience sake.

[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
 
public static void RefreshWindowsExplorer()
{
    // Refresh the desktop
    SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
 
    // Refresh any open explorer windows
    // based on http://stackoverflow.com/questions/2488727/refresh-windows-explorer-in-win7
    Guid CLSID_ShellApplication = new Guid("13709620-C279-11CE-A49E-444553540000");
    Type shellApplicationType = Type.GetTypeFromCLSID(CLSID_ShellApplication, true);
 
    object shellApplication = Activator.CreateInstance(shellApplicationType);
    object windows = shellApplicationType.InvokeMember("Windows", System.Reflection.BindingFlags.InvokeMethod, null, shellApplication, new object[] { });
 
    Type windowsType = windows.GetType();
    object count = windowsType.InvokeMember("Count", System.Reflection.BindingFlags.GetProperty, null, windows, null);
    for (int i = 0; i < (int)count; i++)
    {
        object item = windowsType.InvokeMember("Item", System.Reflection.BindingFlags.InvokeMethod, null, windows, new object[] { i });
        Type itemType = item.GetType();
 
        // Only refresh Windows Explorer, without checking for the name this could refresh open IE windows
        string itemName = (string)itemType.InvokeMember("Name", System.Reflection.BindingFlags.GetProperty, null, item, null);
        if (itemName == "Windows Explorer")
        {
            itemType.InvokeMember("Refresh", System.Reflection.BindingFlags.InvokeMethod, null, item, null);
        }
    }
}
Advertisement

5 comments

  1. sumit says:

    But it does not reload the registry changes.

  2. Brian says:

    When compiled into my exe, this code throws an exception “Access is denied” from the line:
    object windows = shellAPplicaitonType.InvokeMember…
    Any ideas why that is?  It runs in the debug mode in the debugger no problem, but not when compiled into an exe (debug or release).  Thanks!

  3. Calvin says:

    This helped a ton with a PowerShell script I was working on. Thanks!

Leave a Reply