gpt4 book ai didi

c# - 检测物体/可移动介质的插入

转载 作者:太空狗 更新时间:2023-10-30 01:11:50 25 4
gpt4 key购买 nike

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

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

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 时它永远不会被击中。因为我根本没有搞砸过这个,而且我在网上看到的所有示例都只是引用了相同的源代码(有细微的变化)

最佳答案

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");
}

关于c# - 检测物体/可移动介质的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1662794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com