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

CK CK 3788 
Created at
Updated at  
681 0 0

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,  
                                          // 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:

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();    
}

 

Tags CAsyncSocket Removable Disk Detection Removable Media Detection SHCNE_DISKEVENTS SHCNE_MEDIAINESERTED SHChangeNotifyRegister SHNE_MEDIAREMOVED WM_DEVICECHANGE WM_USER_MEDIACHANGED Facebook X
Comments 0
Similar posts
  1. Get The Drive Type
    497
  1. How to detect resource leaks in a Form
    939
  2. The best way to enable and disable buttons, menu items and toolbar buttons
    667
  3. How to exit from a console application
    811
  4. How to restrict a program to a single instance
    729
  5. Compress and decompress strings in C#
    971
  6. Graphics in C# - Irregular Forms
    908
  7. Extracting the Country from IP Address
    468
  8. How to run shell command by MFC ?
    435
  9. Binary Search Sample Code
    405
  10. Double Linked List based in C++
    796
  11. String Replace Function For C#
    1,547
  12. How to print character in C# by ASCII code
    476
  13. MFC based World Wide Web HTTP Server Source Code
    459
  14. Creating and Using a CAsyncSocket Object to use CAsyncSocket
    472
  15. UDP Send and Receive Using CAsyncSocket
    1,204
  16. Adding Custom Paper Sizes To Named Printers
    647
  17. Print HTML In C# With Or Without The Web Browser Control And The Print Dialog
    972
  18. A Customizable Printing Text Class
    432
  19. Simplified .NET Printing In C#
    692
  20. How To Print Text In C#
    455
  21. C# Lists
    1,151
  22. Simple Example of IF/THEN using C#
    1,265
  23. Fast and Good Keyboard/Mouse Test without the message handler
    982
  24. Simple CGI Programming in C
    545
  25. C++ CGI Example working on Apache
    484
  26. Simple C# CGI working on Apache
    480
  27. How to send binary data through C# CGI app?
    994
  28. Interacting With TinyPic From C#
    1,303
  29. Creating A Watched Folder With Assigned Events
    1,658
  30. Calling Your Main Thread From A Worker Thread In C#
    546
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260