/// <summary> /// 构造函数 /// </summary> /// <param name="insert"></param> /// <param name="remove"></param> public USBListener(USBChangeHandler change, USBHandler insert, USBHandler remove) { try { ManagementScope Scope = new ManagementScope("root\\CIMV2"); Scope.Options.EnablePrivileges = true; // USB插入监视 WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 5), "TargetInstance isa 'Win32_USBControllerDevice'"); InsertEvent = new ManagementEventWatcher(Scope, InsertQuery); InsertEvent.EventArrived += _USBInsert; InsertEvent.Start(); // USB拔出监视 WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent", new TimeSpan(0, 0, 5), "TargetInstance isa 'Win32_USBControllerDevice'"); RemoveEvent = new ManagementEventWatcher(Scope, RemoveQuery); RemoveEvent.EventArrived += _USBRemove; RemoveEvent.Start(); USBInsertEvent += insert; USBRemoveEvent += remove; USBChangeEvent += change; } catch { } }
private static void Main(string[] args) { Console.WriteLine("Starting test..."); Console.WriteLine(Path.Combine(Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar)), "ddc_config.json")); var modelRegex = new Regex(@"model\((.*?)\)"); var sourcesRegex = new Regex(@"(?<=\s)60\((.*?)\)"); MonitorController.GetDevices(handles => { foreach (var h in handles) { Console.WriteLine("Display found: " + h.szPhysicalMonitorDescription + " (" + h.hPhysicalMonitor.ToInt64() + ")"); var caps = h.GetVCPCapabilities(); Console.WriteLine(caps); Console.WriteLine(" => Model: " + modelRegex.Match(caps).Groups[1].Value); Console.WriteLine(" => Supported sources: " + string.Join("; ", sourcesRegex.Match(caps).Groups[1].Value.Split(' '))); } }); Console.WriteLine("Starting USB test..."); var usbHandler = new USBHandler(); Console.WriteLine("Press any key to end test, USB actions will be displayed now."); Console.ReadKey(true); Console.WriteLine("Test done!"); }
/// <summary> /// 停止USB设备监控 /// </summary> public void Stop() { InsertEvent?.Stop(); InsertEvent = null; RemoveEvent?.Stop(); RemoveEvent = null; USBInsertEvent = null; USBRemoveEvent = null; Token.Cancel(); }
/// <summary> /// 构造函数 /// </summary> /// <param name="insert"></param> /// <param name="remove"></param> public USBStorageListener(USBChangeHandler change, USBHandler insert, USBHandler remove) { USBInsertEvent += insert; USBRemoveEvent += remove; USBChangeEvent += change; }