Notification when inserting removable drive


Is it possible to get notified when the user inserts a removable drive, like some USB stick, into the computer. So the code can react?


It might be possible… I’ve never looked into how that sort of thing is done.


I think on Windows it might work somehow like this (just wrote this quickly without testing):

// 'drive' -> a: = 0, b: = 1, c: = 2, ...
// 'status' -> 0=removed, 1=inserted
void driveChanged(char drive, int status)

if (msg.message==WM_DEVICECHANGE)
	int status=-1;
	if (msg.wParam==DBT_DEVICEARRIVAL) status=1;
	else if (msg.wParam==DBT_DEVICEREMOVECOMPLETE) status=0;

	if (status<0) return;


	if (p->dbch_devicetype == DBT_DEVTYP_VOLUME)
		DWORD mask=p2->dbcv_unitmask;
		for (int i=0; i<32; i++)
			bool b= mask & 1;
			if (b) 
				driveChanged(i, status);


I would be happy to see this too :smiley:

On Mac it’s something like

pascal OSStatus VolumeEventHandler (EventHandlerCallRef eventHandlerCallRef, EventRef eventRef, void* userData)

  UInt32 eventKind = GetEventKind(eventRef);
  UInt32 eventClass = GetEventClass (eventRef);
  switch (eventClass)
    case kEventClassVolume:
      FSVolumeRefNum refNum = 0;
      GetEventParameter (eventRef, kEventParamDirectObject, typeFSVolumeRefNum, 
                         NULL, sizeof(refNum), NULL, &refNum);
      switch (eventKind)
        case kEventVolumeMounted:
        case kEventVolumeUnmounted:
  return noErr;

in the class body
EventHandlerRef   mEventHandlerRef;
EventHandlerProcPtr mEventHandlerUPP;

in the ctor
[code]EventTypeSpec windowEvents[]={ { kEventClassVolume, kEventVolumeMounted}, { kEventClassVolume, kEventVolumeUnmounted} };
  mEventHandlerUPP = NewEventHandlerUPP(::VolumeEventHandler);
  OSErr err = InstallApplicationEventHandler(mEventHandlerUPP, 
                                 (void*) this, 

in the dtor

if (mEventHandlerRef) RemoveEventHandler(mEventHandlerRef);
if (mEventHandlerUPP) DisposeEventHandlerUPP(mEventHandlerUPP);