Notification when inserting removable drive


#1

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?


#2

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


#3

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;

	DEV_BROADCAST_HDR *p=(DEV_BROADCAST_HDR*)msg.lParam;

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

#4

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:
        {
        }
        break;
        case kEventVolumeUnmounted:
        {
        }
        break;
      }
    }
  }
  return noErr;
}[/code]

in the class body
[code]  
EventHandlerRef   mEventHandlerRef;
EventHandlerProcPtr mEventHandlerUPP;
[/code]

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

in the dtor

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

HTH