9

How to catch an event when a new drive is added to My Computer and preferably and when new mount point for some drive is created on a NTFS drive?


I figued out this but it doesn't work on mounted folders:

 _eventWatcher = new ManagementEventWatcher("SELECT * FROM Win32_VolumeChangeEvent");

 _eventWatcher.EventArrived += (o, args) => 
     {switch(args.NewEvent["EventType"].ToString()[0])
         {
             case '2':
                 //mount
                 Debug.WriteLine(args.NewEvent["DriveName"]);
                 break;
             case '3':
                 //unmount
                 break;
         }
     };

 _eventWatcher.Start();

Any ideas?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
user629926
  • 1,910
  • 2
  • 18
  • 43

1 Answers1

7

If you have a form, you can override its WndProc method to catch WM_DEVICECHANGE messages as Eugene mentioned:

private const int WM_DEVICECHANGE = 0x219;

protected override void WndProc(ref Message m)
{
    base.WndProc(m);

    if (m.Msg == WM_DEVICECHANGE)
    {
        // Check m.wParam to see exactly what happened
    }
}
Marty
  • 7,464
  • 1
  • 31
  • 52
  • I will probably need to port my code to windows service some time later so this solution won't work. Thanks anyway. – user629926 Nov 18 '11 at 21:20
  • if you want to do it in a Windows Service you must check this one: http://www.codeproject.com/KB/system/Windows_Services.aspx?msg=2900262 – Davide Piras Nov 18 '11 at 21:55