Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect drive mount event in c#

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?

like image 849
user629926 Avatar asked Nov 18 '11 20:11

user629926


1 Answers

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
    }
}
like image 132
Marty Avatar answered Oct 17 '22 08:10

Marty