Click here to Skip to main content
15,867,594 members
Articles / Desktop Programming / MFC

Using the Shell to Receive Notification of Removable Media Being Inserted or Removed

Rate me:
Please Sign up or sign in to vote.
5.00/5 (12 votes)
20 Nov 20021 min read 188.4K   55   36
Uses the poorly documented SHChangeNotifyRegister function to receive notification upon shell events

Introduction

Recently, I needed to determine when removable media, such as a zip disk or media card, had been inserted by the user.

I initially looked into the WM_DEVICECHANGE broadcast message only to realise this supports CDROMs and little else. Fortunately, there is another way via the shell, through the scarcely documented SHChangeNotifyRegister function.

We can register to be informed by the shell when certain events of interest occur. The events are numerous - covering when a drive is added or removed, files are renamed, etc. However of particular interest here are the notifications for media being inserted or removed.

It's scarcely rocket science but piecing the various bits of information together to utilise this functionality took far longer than it should have. I was amazed there was no article here on CodeProject covering this, so figured I should rectify that!

Implementation

You will need the following includes and definition:

C++
#include <shlobj.h>
#define WM_USER_MEDIACHANGED WM_USER+88

Together with a member variable to release the request later:

C++
ULONG m_ulSHChangeNotifyRegister;

Nullify the member variable in your constructor, then register to be notified by the shell (perhaps in OnInitDialog for example):

C++
CMyWnd::CMyWnd()
{
    ulSHChangeNotifyRegister = NULL;
}

BOOL CMyWnd::OnInitDialog() 
{
    CWnd::OnInitDialog();

    // Request notification from shell of media insertion -
    // allows us to detect removable media or a multimedia card
    HWND hWnd = GetSafeHwnd();
    LPITEMIDLIST ppidl;
    if(SHGetSpecialFolderLocation(hWnd, CSIDL_DESKTOP, &ppidl) == NOERROR)
    {
        SHChangeNotifyEntry shCNE;
        shCNE.pidl = ppidl;
        shCNE.fRecursive = TRUE;

        // Returns a positive integer registration identifier (ID).
        // Returns zero if out of memory or in response to invalid parameters.
        m_ulSHChangeNotifyRegister = SHChangeNotifyRegister(hWnd,  
                                          // Hwnd to receive notification
                SHCNE_DISKEVENTS,                          
                                          // Event types of interest (sources)
                SHCNE_MEDIAINSERTED|SHCNE_MEDIAREMOVED,    
                                          // Events of interest - use 
                                          // SHCNE_ALLEVENTS for all events
                WM_USER_MEDIACHANGED,     
                                          // Notification message to be sent 
                                          // upon the event
                1,                         
                                          // Number of entries in the pfsne array
                &shCNE);  // Array of SHChangeNotifyEntry structures that 
                          // contain the notifications. This array should 
                          // always be set to one when calling SHChnageNotifyRegister
                          // or SHChangeNotifyDeregister will not work properly.
    
        ASSERT(m_ulSHChangeNotifyRegister != 0);    // Shell notification failed
    }
    else
        ASSERT(FALSE);    // Failed to get desktop location
}

Add a message handler to your message map for the notification message:

C++
ON_MESSAGE(WM_USER_MEDIACHANGED, OnMediaChanged)

Together with the corresponding declaration:

C++
afx_msg LRESULT OnMediaChanged(WPARAM, LPARAM);

Then deal with the message as desired:

C++
// The lParam value contains the event SHCNE_xxxx
// The wParam value supplies the SHNOTIFYSTRUCT

typedef struct {
    DWORD dwItem1;    // dwItem1 contains the previous PIDL or name of the folder. 
    DWORD dwItem2;    // dwItem2 contains the new PIDL or name of the folder. 
} SHNOTIFYSTRUCT;

LRESULT CMyWnd::OnMediaChanged(WPARAM wParam, LPARAM lParam)
{
    SHNOTIFYSTRUCT *shns = (SHNOTIFYSTRUCT *)wParam;
    CString strPath, strMsg;

    switch(lParam)
    {
        case SHCNE_MEDIAINSERTED:        // media inserted event
        {
            strPath = GetPathFromPIDL(shns->dwItem1);
            if(!strPath.IsEmpty())
            {
                // Process strPath as required, for now a simple message box
                strMsg.Format("Media inserted into %s", strPath);
                AfxMessageBox(strMsg);
            }
        }
        case SHCNE_MEDIAREMOVED:        // media removed event
        {
            strPath = GetPathFromPIDL(shns->dwItem1);
            if(!strPath.IsEmpty())
            {
                // Process strPath as required, for now a simple message box
                strMsg.Format("Media removed from %s", strPath);
                AfxMessageBox(strMsg);
            }
        }
        //case SHCNE_xxxx:  Add other events processing here
    }
    return NULL;
}

CString CMyWnd::GetPathFromPIDL(DWORD pidl)
{
    char sPath[MAX_PATH];
    CString strTemp = _T("");
    if(SHGetPathFromIDList((struct _ITEMIDLIST *)pidl, sPath))
        strTemp = sPath;
    
    return strTemp;
}

Finally, deregister your request when no longer required:

C++
void CMyWnd::OnDestroy() 
{
    if(m_ulSHChangeNotifyRegister)
        VERIFY(SHChangeNotifyDeregister(m_ulSHChangeNotifyRegister));

    CWnd::OnDestroy();    
}

References

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below.

A list of licenses authors might use can be found here.


Written By
Software Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCould you give me a full demo source? Pin
OatmealPirate18-Oct-11 23:54
OatmealPirate18-Oct-11 23:54 
GeneralSame message received twice Pin
nanfang24-May-08 9:57
nanfang24-May-08 9:57 
GeneralTo check whether any USB device is connected Pin
Vjys21-Feb-07 3:16
Vjys21-Feb-07 3:16 
GeneralRe: To check whether any USB device is connected Pin
bzucko1-Mar-07 23:54
bzucko1-Mar-07 23:54 
GeneralConsole App Pin
Member 146901222-Mar-05 21:53
Member 146901222-Mar-05 21:53 
GeneralRe: Console App Pin
pada445-Apr-06 12:28
pada445-Apr-06 12:28 
QuestionNo notification messages for floppy inserted or removed? Pin
Wincax14-Dec-04 22:19
Wincax14-Dec-04 22:19 
AnswerRe: No notification messages for floppy inserted or removed? Pin
Obliterator15-Dec-04 0:16
Obliterator15-Dec-04 0:16 
GeneralRe: No notification messages for floppy inserted or removed? Pin
ThatsAlok22-Feb-05 19:08
ThatsAlok22-Feb-05 19:08 
GeneralWhen app not running Pin
bryce2-Jun-04 20:59
bryce2-Jun-04 20:59 
GeneralRe: When app not running Pin
Obliterator3-Jun-04 1:12
Obliterator3-Jun-04 1:12 
GeneralRe: When app not running Pin
bryce3-Jun-04 2:08
bryce3-Jun-04 2:08 
GeneralLinker error Pin
Oyvind10-May-04 20:04
Oyvind10-May-04 20:04 
GeneralRe: Linker error Pin
Obliterator11-May-04 4:24
Obliterator11-May-04 4:24 
Generalthis doesn't compile Pin
Anonymous23-Apr-04 18:05
Anonymous23-Apr-04 18:05 
GeneralRe: this doesn't compile Pin
HakanErd25-Apr-04 10:15
HakanErd25-Apr-04 10:15 
GeneralExcept when Autorun is off Pin
Griffter UK15-May-03 23:43
Griffter UK15-May-03 23:43 
Generalsome remarks Pin
umeca7427-Nov-02 0:57
umeca7427-Nov-02 0:57 
GeneralRe: some remarks Pin
Obliterator27-Nov-02 4:29
Obliterator27-Nov-02 4:29 
GeneralRe: some remarks Pin
umeca7428-Nov-02 0:24
umeca7428-Nov-02 0:24 
GeneralI cannot compile this Pin
24-Nov-02 20:17
suss24-Nov-02 20:17 
I have Windows 2000 SP2, VC++ 6.0 and Platform SDK August 2002. SHChangeNotifyRegister function doesn't exist in shlobj.h (and also SHChangeNotifyDeregister, SHChangeNotifyEntry). I would like to test this using LoadLibrary, but I don't see SHChangeNotifyRegister in list of exported functions of shell32.dll.
GeneralThe same with SP3 Pin
567890123424-Nov-02 21:51
567890123424-Nov-02 21:51 
GeneralRe: The same with SP3 Pin
Obliterator25-Nov-02 2:57
Obliterator25-Nov-02 2:57 
Generalfor reference (slightly off topic) Pin
mgama21-Nov-02 7:19
mgama21-Nov-02 7:19 
GeneralRe: for reference (slightly off topic) Pin
Obliterator21-Nov-02 15:09
Obliterator21-Nov-02 15:09 

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

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