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

CK1820 
Created at Aug 28, 2007 00:34:07 
45   0   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: C++ CAsyncSocket Removable Disk Detection Removable Media Detection SHCNE_DISKEVENTS SHCNE_MEDIAINESERTED SHChangeNotifyRegister SHNE_MEDIAREMOVED WM_DEVICECHANGE WM_USER_MEDIACHANGED Share on Facebook Share on X

◀ PREVIOUS
Adding Custom Paper Sizes To Named Printers
▶ NEXT
UDP Send and Receive Using CAsyncSocket
  Comments 0
Login for comment
SIMILAR POSTS

UDP Send and Receive Using CAsyncSocket (created at Aug 28, 2007)

Creating and Using a CAsyncSocket Object to use CAsyncSocket (created at Aug 28, 2007)

MFC based World Wide Web HTTP Server Source Code (created at Aug 28, 2007)

Fast and Good Keyboard/Mouse Test without the message handler (created at Aug 27, 2007)

Simple CGI Programming in C (created at Aug 27, 2007)

C++ CGI Example working on Apache (created at Aug 27, 2007)

Get The Drive Type (created at Aug 25, 2007)

Double Linked List based in C++ (created at Sep 08, 2007)

Binary Search Sample Code (created at Sep 08, 2007)

How to run shell command by MFC ? (created at Sep 09, 2007)

How to search file on certain directory ? (created at Jun 15, 2008)

How to call SetTimer function on MFC CDialog class ? (created at Jul 30, 2008)

How to load HTML resource on MFC ? (updated at Dec 17, 2023)

URL Encode, Decode function for MFC (updated at Dec 20, 2023)

KMP String Matching Algorithm (created at Jul 21, 2010)

OTHER POSTS IN THE SAME CATEGORY

How to detect resource leaks in a Form (created at Sep 25, 2007)

The best way to enable and disable buttons, menu items and toolbar buttons (created at Sep 25, 2007)

How to exit from a console application (created at Sep 25, 2007)

How to restrict a program to a single instance (created at Sep 25, 2007)

Compress and decompress strings in C# (created at Sep 25, 2007)

Graphics in C# - Irregular Forms (created at Sep 25, 2007)

Extracting the Country from IP Address (created at Sep 25, 2007)

How to run shell command by MFC ? (created at Sep 09, 2007)

Binary Search Sample Code (created at Sep 08, 2007)

Double Linked List based in C++ (created at Sep 08, 2007)

String Replace Function For C# (created at Aug 28, 2007)

How to print character in C# by ASCII code (created at Aug 28, 2007)

MFC based World Wide Web HTTP Server Source Code (created at Aug 28, 2007)

Creating and Using a CAsyncSocket Object to use CAsyncSocket (created at Aug 28, 2007)

UDP Send and Receive Using CAsyncSocket (created at Aug 28, 2007)

Adding Custom Paper Sizes To Named Printers (created at Aug 27, 2007)

Print HTML In C# With Or Without The Web Browser Control And The Print Dialog (created at Aug 27, 2007)

A Customizable Printing Text Class (created at Aug 27, 2007)

Simplified .NET Printing In C# (created at Aug 27, 2007)

How To Print Text In C# (created at Aug 27, 2007)

C Sharp Lists (created at Aug 27, 2007)

Simple Example Of IF/THEN Using C# (created at Aug 27, 2007)

Fast and Good Keyboard/Mouse Test without the message handler (created at Aug 27, 2007)

Simple CGI Programming in C (created at Aug 27, 2007)

C++ CGI Example working on Apache (created at Aug 27, 2007)

Simple C# CGI working on Apache (created at Aug 27, 2007)

How to send binary data through C# CGI app? (created at Aug 27, 2007)

Interacting With TinyPic From C# (created at Aug 26, 2007)

Creating A Watched Folder With Assigned Events (created at Aug 26, 2007)

Calling Your Main Thread From A Worker Thread In C# (created at Aug 26, 2007)

UPDATES

Creating a Pinterest-Style Card Layout with Bootstrap and Masonry (created at Apr 24, 2024)

Mastering Excel Data Importation in PHP (updated at Apr 24, 2024)

JSON format control in PHP (updated at Apr 24, 2024)

Equal Height Blocks in Bootstrap with JavaScript (created at Apr 22, 2024)

How to convert integer to text string ? (updated at Apr 22, 2024)

Checking similarity between two strings in PHP (updated at Apr 21, 2024)

Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file (updated at Apr 21, 2024)

How do I determine the client IP type (IPv4/IPv6) in PHP (updated at Apr 16, 2024)

How do I determine the client IP type in Python - IPv4 or IPv6 (updated at Apr 13, 2024)

Getting Started with PyTorch: A Beginner's Guide to Building Your First Neural Network (updated at Apr 09, 2024)

Predicting Buyer Preferences with PyTorch: A Deep Learning Approach (updated at Apr 09, 2024)

Forecasting the Weather with PyTorch: A Beginner's Guide to Temperature Prediction (created at Apr 09, 2024)

PyTorch example to Forcast Stock Price based on 10 days Dataset (created at Apr 09, 2024)

Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python (created at Apr 08, 2024)

Harnessing the Power of Random Forest Algorithm in Python (created at Apr 08, 2024)

Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python (created at Apr 08, 2024)

Forecasting with Linear Regression and KNN Regression in Python (updated at Apr 07, 2024)

What is 302 Found Redirection in HTTP 1.1? (created at Apr 04, 2024)

Mastering Random Forest Regression: A Comprehensive Guide with Python Examples (updated at Apr 01, 2024)

Python Implementation of Linear Regression (updated at Apr 01, 2024)

Mastering Supervised Machine Learning with Python: A Comprehensive Guide (created at Apr 01, 2024)

Mastering AI: A Beginner's Guide to Python Programming and Beyond (created at Apr 01, 2024)

How do I create animated background for Google Meet? (updated at Mar 28, 2024)

Building a Simple DNS Server in Delphi with TTL Support (created at Mar 16, 2024)

How to force cookies, disable php sessid in URL ? (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records (updated at Mar 16, 2024)

Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records (created at Mar 16, 2024)

Building a Basic DNS Server in PHP/Python: A Beginner's Guide (updated at Mar 15, 2024)

Dynamic DNS Made Easy: Building a Python-Based Solution (created at Mar 15, 2024)

Exploring the Depths of Data Transfer: sendfile vs. kTLS (created at Mar 15, 2024)