Click here to Skip to main content
Licence Ms-PL
First Posted 16 Oct 2002
Views 105,787
Downloads 1,709
Bookmarked 55 times

Shell Notifications in C#

By | 16 Oct 2002 | Article
Shows how to receive shell notifications for specified directories
Shell Notifications

Introduction

When you build an application that shows files or directories of the local computer, you must know if the files already exist. You can add refresh functions but there is another way to know in real time when something has changed by using the SHChangeNotifyRegister API.

For a complete overview of shell change notifications, James Holderness made a very useful "Shell Notifications" page.

The structures and enumerations are not listed here but are accessible in the sources.

SHChangeNotifyRegister and SHChangeNotifyUnregister declarations

The API calls are hidden: SHChangeNotifyRegister uses an entry point value of 2 and SHChangeNotifyUnregister uses 4.

using System.Runtime.InteropServices;

[DllImport("shell32.dll", EntryPoint="#2", CharSet=CharSet.Auto)]
private static extern uint SHChangeNotifyRegister(
    IntPtr hWnd,
    SHCNF fSources,
    SHCNE fEvents,
    uint wMsg,
    int cEntries,
    ref SHChangeNotifyEntry pFsne);

[DllImport("shell32.dll", EntryPoint="#4", CharSet=CharSet.Auto)]
[return:MarshalAs(UnmanagedType.Bool)]
private static extern Boolean SHChangeNotifyUnregister(
    ulong hNotify);

Register a handle

When a modification occurs, the shell sends a notification to each registered handle. You have to specify the folder root by the pidl retrieved by the SHGetSpecialFolderLocation API.

[DllImport("shell32.dll", CharSet=CharSet.Auto)]
private static extern uint SHGetSpecialFolderLocation(
    IntPtr hWnd,
    CSIDL nFolder,
    out IntPtr Pidl);

public ulong RegisterChangeNotify(IntPtr hWnd, CSIDL FolderID,
    bool Recursively)
{
    if(notifyid != 0) return(0);
    SHChangeNotifyEntry changeentry = new SHChangeNotifyEntry();

    changeentry.pIdl = GetPidlFromFolderID(hWnd, FolderID);
    changeentry.Recursively = Recursively;

    notifyid = SHChangeNotifyRegister(
        hWnd,
        SHCNF.SHCNF_TYPE | SHCNF.SHCNF_IDLIST,
        SHCNE.SHCNE_ALLEVENTS | SHCNE.SHCNE_INTERRUPT,
        WM_SHNOTIFY,
        1,
        ref changeentry);

    return(notifyid);
}

public Boolean UnregisterChangeNotify()
{
    if(notifyid == 0) return(false);

    if(SHChangeNotifyUnregister(notifyid))
    {
        notifyid = 0;
        return(true);
    }

    return(false);
}

public static IntPtr GetPidlFromFolderID(IntPtr hWnd, CSIDL Id)
{
    IntPtr pIdl = IntPtr.Zero;

    SHGetFolderLocationReturnValues res = 
	    (SHGetFolderLocationReturnValues)
		SHGetSpecialFolderLocation( hWnd,
            Id,
            out pIdl);

    return(pIdl);
}

Notification reception

When you receive a notification, you want to know the type of the operation, the concerned item, and the new value of the item. This information is stored in the SHNOTIFYSTRUCT which the WParam points to. You can then add the new notification to an ArrayList that contains each notification.

public System.Collections.ArrayList NotificationsReceived = 
    new System.Collections.ArrayList();

public bool NotificationReceipt(IntPtr wParam, IntPtr lParam)
{
    SHNOTIFYSTRUCT shNotify = (SHNOTIFYSTRUCT) Marshal.PtrToStructure(
        wParam,
        typeof(SHNOTIFYSTRUCT));

    NotifyInfos info = new NotifyInfos((SHCNE)(int) lParam);
    
    // These notifications are Not supported
    if(info.Notification == SHCNE.SHCNE_FREESPACE ||
        info.Notification == SHCNE.SHCNE_UPDATEIMAGE)
        return(false);
    
    info.Item1 = GetPathFromPidl(shNotify.dwItem1);
    info.Item2 = GetPathFromPidl(shNotify.dwItem2);
    
    // Was this notification in the received notifications ?
    if(NotificationsReceived.Contains(info))
	    return(false);

    NotificationsReceived.Add(info);

    return(true);
}

If the notification was not in the NotificationsReceived list, the NotificationReceipt method adds it to the list and returns true.

Now, a new case must be added in the WndProc of the Form, so that the notifications can be handled:

The code below handles the notification by checking if it has been added to the list.  if it isn't, NotificationReceipt returns true and the code calls NewOperation passing in the NotifyInfos struct corresponding to the latest event.

private ShellNotifications Notifications = new ShellNotifications();

protected override void WndProc(ref Message m)
{
    switch(m.Msg)
    {
        case (int) ShellNotifications.WM_SHNOTIFY:
            bool bAdded = Notifications.NotificationReceipt(
                m.WParam, m.LParam);

            if( bAdded )
            {
                NotifyInfos nis = (NotifyInfos) 
                    Notifications.NotificationsReceived[
                        Notifications.NotificationsReceived.Count - 1];

                NewOperation(nis);
            }

            break;
    }
    base.WndProc(ref m);
}

private void NewOperation(NotifyInfos infos)
{
    //
    // You can add your code here.
    // The line below is an example : 
    // it adds the operation informations in a listview.
    //
    listView1.Items.Add(
        new ListViewItem(
            new string[] {
                infos.Notification.ToString(),
                infos.Item1,
                infos.Item2}));
}

Revision History

  • October 17, 2002 - Initial posting

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

Thomas Caudal

Web Developer

France France

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembermalac19:26 13 Jul '10  
QuestionCompact framework compatibility?? Pinmembernuttynibbles7:29 20 Feb '10  
GeneralSHChangeNotifyUnregister Pinmemberbzucko2:52 5 Mar '07  
Generalthis only works from explorer PinmemberBilliebub1:16 12 Feb '07  
GeneralGetDisplayNameFromPidl PinmemberLesuran3:44 9 Nov '04  
GeneralRe: GetDisplayNameFromPidl Pinmemberfelix at home23:07 24 Sep '06  
GeneralGet path name directly instead pidls PinmemberFreigeist6:34 21 Sep '04  
Questioncan not log all changes Pinmemberzbshen7:43 19 May '04  
AnswerRe: can not log all changes PinmemberSimmRein16:58 10 Sep '09  
QuestionHow to watch for viewing & executing actions Pinmemberzuken2113:54 2 Apr '04  
GeneralCan't download although i logged in - that really bugs me! PinsussAnonymousAnNoyedAndRageous16:26 25 Jan '03  
GeneralFileSystemWatcher has platform issues PinmemberJames Cadd7:41 17 Oct '02  
GeneralRe: FileSystemWatcher has platform issues PinmemberJesper22:29 17 Oct '02  
GeneralRe: FileSystemWatcher has platform issues PinmemberJames Cadd1:46 18 Oct '02  
GeneralRe: FileSystemWatcher has platform issues PinmemberJesper1:56 18 Oct '02  
GeneralRe: FileSystemWatcher has platform issues Pinmembermalac19:27 13 Jul '10  
GeneralRe: System.IO.FileSystemWatcher PinmemberHeath Stewart8:49 17 Oct '02  
GeneralSystem.IO.FileSystemWatcher PinmemberJesper2:51 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PineditorPaul Watson3:34 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PinmemberDaniel Turini3:40 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PineditorPaul Watson3:46 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PinmemberDaniel Turini3:56 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PinmemberJesper4:05 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PineditorPaul Watson4:28 17 Oct '02  
GeneralRe: System.IO.FileSystemWatcher PinsussAnonymous7:21 18 Oct '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 17 Oct 2002
Article Copyright 2002 by Thomas Caudal
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid