[英]How to get an insterted USB drive letter in a service project?
I've always used the method of overriding WndProc(ref Message m) to get events for drive inserted/removed and created my own eventarg to return the drive letter. 我一直使用重写WndProc(ref Message m)的方法来获取插入/卸下驱动器的事件,并创建了自己的eventarg以返回驱动器号。 This worked perfectly but now I'm busy developing a service project and obviously cannot use the above-mentioned method.
这很完美,但是现在我正忙于开发服务项目,显然不能使用上述方法。
I'm using now WMI: 我现在正在使用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();
This correctly lets the event fire when a USB flash is plugged in. Now what I need help with is how to get the drive letter (eg E:) from the event? 这可以正确地使事件在插入USB闪存时触发。现在,我需要帮助的是如何从事件中获取驱动器号(例如E :)?
Here is what I have played around in my event so far: 到目前为止,这是我在比赛中所玩的游戏:
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);
}
}
I can't get the drive letter from "Properties". 我无法从“属性”获得驱动器号。 Is there a way to get the drive letter?
有没有办法获取驱动器号? Or do I need to look at the problem from a completely different angle?
还是我需要从完全不同的角度看问题?
After a lot of frustration, I got it working! 经过很多挫折后,我开始工作了!
the solution is, instead of using: 解决方案是,而不是使用:
creationQuery.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
Change it to: 更改为:
creationQuery.Condition = @"TargetInstance ISA 'Win32_LogicalDisk'";
Now in the event function, the properties from the EventArrivedEventArgs e
will include drive letter. 现在在事件函数中,
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.Value contains the Drive letter when property.Name = "Name" 当property.Name =“ Name”时,property.Value包含驱动器号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.