title: Detecting when a volume is mounted in Windows with Delphi
body: <p>I am trying to understand the documentation at MSDN regarding Device Events
  and how to trigger a notification whenever a volume has been mounted.</p>
  
  <p>I have managed to do this for USB devices using information presented in the following post: <a href="https://stackoverflow.com/questions/7949782/detect-usb-drive-device-using-delphi">detect usb drive/device using delphi</a></p>
  
  <p>as well as other information found on the internet,
  but I have noticed that it would be easier to detect when a volume has been mounted directly.</p>
  
  <p>So my question is: how do I implement Device Events handling in my Delphi app?</p>
  
  <p>I am looking at the following documentation: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa363217(v=vs.85).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/windows/desktop/aa363217(v=vs.85).aspx</a></p>
  
  <p>But I can't really figure out how to get it up and running.</p>
  
  <p>So far I have tried the following code, which compiles properly,
  but nothing happens, please push me in the right direction:</p>
  
  <pre><code>PDevBroadcastHdr  = ^DEV_BROADCAST_HDR;
    DEV_BROADCAST_HDR = packed record
      dbch_size       : DWORD;
      dbch_devicetype : DWORD;
      dbch_reserved   : DWORD;
    end;
  
    PDevBroadcastHandle = ^DEV_BROADCAST_HANDLE;
    DEV_BROADCAST_HANDLE = packed record
      dbch_size       : DWORD       ;
      dbch_devicetype : DWORD       ;
      dbch_reserved   : DWORD       ;
      dbch_handle     : THandle     ;
      dbch_hdevnotify : HDEVNOTIFY  ;
      dbch_eventguid  : TGUID       ;
      dbch_nameoffset : LongInt     ;
      dbch_data       : byte        ;
    end;
  
  ...
  
  
  procedure WMDeviceChange(var Msg: TMessage);
  
  const
    DBT_DEVTYP_HANDLE = $0006;
    GUID_IO_VOLUME_MOUNT: TGUID = '{B5804878-1A96-11D2-8FFD-00A0C9A06D32}';
  
  ...
  
  function TForm1.RegisterThis: Boolean;
  var
    dbv: DEV_BROADCAST_HANDLE;
    Size: Integer;
    r: Pointer;
  begin
    Size := SizeOf(DEV_BROADCAST_HANDLE);
    ZeroMemory(@dbv, Size);
    dbv.dbch_size := Size;
    dbv.dbch_devicetype := DBT_DEVTYP_HANDLE;
    dbv.dbch_reserved := 0;
    dbv.dbch_handle  := 0;
    dbv.dbch_hdevnotify := nil;
    dbv.dbch_eventguid := GUID_IO_VOLUME_MOUNT;
    dbv.dbch_nameoffset := 0;
    dbv.dbch_data := 0;
  
    r := RegisterDeviceNotification(FWindowHandle, @dbv, DEVICE_NOTIFY_WINDOW_HANDLE);
  
  
    if Assigned(r) then Result := True;
  end;
  
  
  procedure TForm1.WMDeviceChange(var Msg: TMessage);
  var
    VData: PDevBroadcastHandle;
  begin
    ShowMessage('Hello!');
  end;
  </code></pre>