Detect drive mount event in c#

萝らか妹 提交于 2019-12-18 16:09:01

问题


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?


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/8188876/detect-drive-mount-event-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!