Click here to Skip to main content
Licence 
First Posted 20 Nov 2002
Views 122,617
Bookmarked 53 times

Using the shell to receive notification of removable media being inserted or removed.

By | 20 Nov 2002 | Article
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.

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

Implementation

You will need the following includes and definition:
#include <shlobj.h>
#define WM_USER_MEDIACHANGED WM_USER+88
Together with a member variable to release the request later:
ULONG m_ulSHChangeNotifyRegister;
Nullify the member variable in your constructor, then register to be notified by the shell (perhaps in OnInitDialog for example):
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,  <BR>                                          // Hwnd to receive notification
                SHCNE_DISKEVENTS,                          <BR>                                          // Event types of interest (sources)
                SHCNE_MEDIAINSERTED|SHCNE_MEDIAREMOVED,    <BR>                                          // Events of interest - use <BR>                                          // SHCNE_ALLEVENTS for all events
                WM_USER_MEDIACHANGED,     <BR>                                          // Notification message to be sent <BR>                                          // upon the event
                1,                         <BR>                                          // Number of entries in the pfsne array
                &shCNE);  // Array of SHChangeNotifyEntry structures that <BR>                          // contain the notifications. This array should <BR>                          // 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:
ON_MESSAGE(WM_USER_MEDIACHANGED, OnMediaChanged)
Together with the corresponding declaration:
afx_msg LRESULT OnMediaChanged(WPARAM, LPARAM);
Then deal with the message as desired:
// 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:
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

About the Author

Obliterator

Software Developer

United Kingdom United Kingdom

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
QuestionCould you give me a full demo source? PinmemberVioletPirate23:54 18 Oct '11  
GeneralSame message received twice Pinmembernanfang9:57 24 May '08  
GeneralTo check whether any USB device is connected PinmemberMember #38461013:16 21 Feb '07  
GeneralRe: To check whether any USB device is connected Pinmemberbzucko23:54 1 Mar '07  
GeneralConsole App PinmemberBeng Heng21:53 22 Mar '05  
GeneralRe: Console App Pinmemberpada4412:28 5 Apr '06  
QuestionNo notification messages for floppy inserted or removed? PinmemberMicheal Huang22:19 14 Dec '04  
AnswerRe: No notification messages for floppy inserted or removed? PinmemberObliterator0:16 15 Dec '04  
GeneralRe: No notification messages for floppy inserted or removed? PinmemberThatsAlok19:08 22 Feb '05  
Obliterator wrote:
Who uses floppies these days anyhow?
 
ME!!!!Smile | :)
 
Your Article is Simply.........................Great!!!, i am seraching for quite long time.
 
Thanks
 

"I Think this Will Help"
[Vote One Here,.....]
 visit me at http://www.thisisalok.tk

GeneralWhen app not running Pinmemberbryce20:59 2 Jun '04  
GeneralRe: When app not running PinmemberObliterator1:12 3 Jun '04  
GeneralRe: When app not running Pinmemberbryce2:08 3 Jun '04  
GeneralLinker error PinmemberOyvind20:04 10 May '04  
GeneralRe: Linker error PinmemberObliterator4:24 11 May '04  
Generalthis doesn't compile PinsussAnonymous18:05 23 Apr '04  
GeneralRe: this doesn't compile PinmemberHakanErd10:15 25 Apr '04  
GeneralExcept when Autorun is off PinmemberMrLeeGriffiths23:43 15 May '03  
Generalsome remarks Pinmemberumeca740:57 27 Nov '02  
GeneralRe: some remarks PinmemberObliterator4:29 27 Nov '02  
GeneralRe: some remarks Pinmemberumeca740:24 28 Nov '02  
GeneralI cannot compile this PinmemberAlex F20:17 24 Nov '02  
GeneralThe same with SP3 PinmemberAlex F21:51 24 Nov '02  
GeneralRe: The same with SP3 PinmemberObliterator2:57 25 Nov '02  
Generalfor reference (slightly off topic) Pinmembermgama7:19 21 Nov '02  
GeneralRe: for reference (slightly off topic) PinmemberObliterator15:09 21 Nov '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
Web02 | 2.5.120528.1 | Last Updated 21 Nov 2002
Article Copyright 2002 by Obliterator
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid