我一直使用覆盖 WndProc(ref Message m) 的方法来获取插入/移除驱动器的事件,并创建我自己的 eventarg 以返回驱动器号。这非常有效,但现在我正忙于开发服务项目,显然不能使用上述方法。
我现在使用的是 WMI:
//insert
WqlEventQuery creationQuery = new WqlEventQuery();
creationQuery.EventClassName = "__InstanceCreationEvent";
creationQuery.WithinInterval = new TimeSpan(0, 0, 2);
creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
ManagementEventWatcher creationWatcher = new ManagementEventWatcher(creationQuery);
creationWatcher.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
creationWatcher.Start();
当插入 USB 闪存时,这会正确地触发事件。现在我需要帮助的是如何从事件中获取驱动器号(例如 E:)?
到目前为止,这是我在事件中玩过的游戏:
internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
{
EventLog.WriteEntry("USB PLUGGED IN!");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
EventLog.WriteEntry(property.Name + " = " + property.Value);
}
}
我无法从“属性”中获取驱动器号。有没有办法获取驱动器号?还是我需要从一个完全不同的角度看问题?
最佳答案
在经历了很多挫折之后,我成功了!
解决方案是,而不是使用:
creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
将其更改为:
creationQuery.Condition = @"TargetInstance ISA 'Win32_LogicalDisk'";
现在在事件函数中,EventArrivedEventArgs e
的属性将包括驱动器号。
internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
{
Console.WriteLine("USB PLUGGED IN!");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
if (property.Name == "Name")
Console.WriteLine(property.Name + " = " + property.Value);
}
}
当 property.Name = "Name"时,property.Value 包含盘符
关于c# - 如何在服务项目中获取插入的U盘盘符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20072085/