/// <summary>Starts the monitoring of device.</summary> public void Monitor(string path, MediaEvent mediaEvent) { if (null == mediaEvent) { throw new ArgumentException("Media event cannot be null!"); } Exit(); //In case same class was called make sure only one instance is running m_logicalDrive = GetLogicalDrive(path); //Keep logical drive to check WqlEventQuery wql; var observer = new ManagementOperationObserver(); //Bind to local machine var opt = new ConnectionOptions(); //Sets required privilege opt.EnablePrivileges = true; var scope = new ManagementScope("root\\CIMV2", opt); try { wql = new WqlEventQuery(); wql.EventClassName = "__InstanceCreationEvent"; wql.WithinInterval = new TimeSpan(0, 0, 1); //wql.Condition = String.Format(@"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DeviceID = '{0}'", this.m_logicalDrive); wql.Condition = String.Format( @"TargetInstance ISA 'Win32_PnPEntity' and TargetInstance.Name = 'CONTOUR USB'"); m_managementEventWatcher = new ManagementEventWatcher(scope, wql); //Register async. event handler m_managementEventWatcher.EventArrived += mediaEvent.MediaEventArrived; m_managementEventWatcher.Start(); } catch (Exception e) { Exit(); throw new Exception("Media Check: " + e.Message); } }
private static void MeMediaWatcher(object sender, MediaEvent.DriveStatus driveStatus) { Console.WriteLine("Cool!" + driveStatus); }