Csharp/C#教程:检测可移动介质的弹出/插入分享


检测可移动介质的弹出/插入

我正在开发一个项目,我需要能够检测何时插入或移除CD或USB驱动器。 我找到了一些应该做这件事的源代码,但是,当我插入或弹出CD时似乎没有任何事情发生。

有人可以validation来源是否正确,并给我任何关于我在这里做错了什么的指示?

public class MyWindow { ManagementEventWatcher w; private void MyWindow_Loaded(object sender, RoutedEventArgs e) { WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2"); ConnectionOptions opt = new ConnectionOptions(); opt.EnablePrivileges = true; ManagementScope ms = new ManagementScope("root\CIMV2", opt); w = new ManagementEventWatcher(ms, query); w.EventArrived += new EventArrivedEventHandler(w_EventArrived); w.Start(); } private void w_EventArrived(object sender, EventArrivedEventArgs e) { PropertyData pd = e.NewEvent.Properties["TargetInstance"]; } } 

当我在“PropertyData pd = …”行上设置断点时,弹出/插入CD时它永远不会被击中。 因为我根本没有弄乱这个,所以我在网上看到的所有例子都引用了相同的源代码(略有变化)

上述就是C#学习教程:检测可移动介质的弹出/插入分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 using System.Management; public void networkDevice() { try { WqlEventQuery q = new WqlEventQuery(); q.EventClassName = "__InstanceModificationEvent"; q.WithinInterval = new TimeSpan(0, 0, 1); q.Condition = @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 5"; ConnectionOptions opt = new ConnectionOptions(); opt.EnablePrivileges = true; opt.Authority = null; opt.Authentication = AuthenticationLevel.Default; //opt.Username = "Administrator"; //opt.Password = ""; ManagementScope scope = new ManagementScope("\root\CIMV2", opt); ManagementEventWatcher watcher = new ManagementEventWatcher(scope, q); watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); } catch (ManagementException e) { Console.WriteLine(e.Message); } } void watcher_EventArrived(object sender, EventArrivedEventArgs e) { ManagementBaseObject wmiDevice = (ManagementBaseObject)e.NewEvent["TargetInstance"]; string driveName = (string)wmiDevice["DeviceID"]; Console.WriteLine(driveName); Console.WriteLine(wmiDevice.Properties["VolumeName"].Value); Console.WriteLine((string)wmiDevice["Name"]); if (wmiDevice.Properties["VolumeName"].Value != null) Console.WriteLine("CD has been inserted"); else Console.WriteLine("CD has been ejected"); } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/991448.html

(0)
上一篇 2021年12月23日
下一篇 2021年12月23日

精彩推荐