如何获取有关最近连接的USB设备的信息? [英] How do I get information about recently connected USB device?

查看:184
本文介绍了如何获取有关最近连接的USB设备的信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当USB设备与 Win32_DeviceChangeEvent



,但只有3个属性允许查看

  class Win32_DeviceChangeEvent:__ExtrinsicEvent 
{
uint8 SECURITY_DESCRIPTOR [];
uint64 TIME_CREATED;
uint16 EventType;
};

但是我不知道如何获取有关此设备的所有信息。具体来说,其端口和中心,VirtualHubAdress名称等。

 公共枚举EventType 
{已插入
= 2,已删除
= 3
}

public static void RegisterUsbDeviceNotification()
{
var watcher = new ManagementEventWatcher( );
var query = new WqlEventQuery( SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2);
//watcher.EventArrived + =新的EventArrivedEventHandler(watcher_EventArrived);
watcher.EventArrived + =(s,e)=>
{
//这里是我需要获取有关此设备的信息

EventType eventType =(EventType)(Convert.ToInt16(e.NewEvent.Properties [ EventType] 。值));
};

watcher.Query =查询;
watcher.Start();
}

也许我可以使用像这样的东西来做到这一点

  [DllImport( UseFull.dll)] 
private IntpPtr GetAllinfo(params);


解决方案

Win32_DeviceChangeEvent 仅报告发生的事件类型和事件时间(uint64,代表100 -UTC 1601年1月1日之后的纳秒间隔)。如果您还想知道已到达或已删除的内容,则没什么用。


我建议改为使用 WqlEventQuery 类,设置其 EventClassName 到[ __ InstanceOperationEvent ] [4]。

此系统类提供了一个 TargetInstance 属性,可以将该属性强制转换为 ManagementBaseObject ,它也是在设备上提供基本信息的完整管理对象

在这些信息(包括设备的友好名称)中, PNPDeviceID ,可以用来建立其他队列


WqlEventQuery 条件属性可以在此处设置为 TargetInstance ISA'Win32_DiskDrive'

可以将其设置为其他任何感兴趣的 Win32 _ 类。


设置事件侦听器(本地计算机):

(事件处理程序称为 DeviceChangedEvent

  WqlEventQuery查询=新的WqlEventQuery(){
EventClassName = __InstanceOperationEvent,
InternalInterval =新的TimeSpan(0, 0,3),
条件= @ TargetInstance ISA'Win32_DiskDrive'';
};

ManagementScope范围=新的ManagementScope( root?CIMV2);
使用(ManagementEventWatcher moWatcher = new ManagementEventWatcher(作用域,查询))
{
moWatcher.Options.Timeout = ManagementOptions.InfiniteTimeout;
moWatcher.EventArrived + =新的EventArrivedEventHandler(DeviceChangedEvent);
moWatcher.Start();
}

事件处理程序在 e.NewEvent.Properties中接收事件[ TargetInstance] ,表示[Win32_DiskDrive] [7]类的管理对象。

有关可直接在此处使用的属性的信息,请参阅文档。 / p>

e报告的 __ InstanceOperationEvent 派生的关注类别.NewEvent.ClassPath.ClassName ,可以是:


__ InstanceCreationEvent :已检测到新的设备到达。

__ InstanceDeletionEvent :已检测到设备删除。

__ Instance ModificationEvent :现有设备已经过某种修改。


请注意,该事件是在辅助线程中引发的,我们需要 BeginInvoke UI线程以使用新信息更新UI。


请参见此处:获取提供有关设备的大部分可用信息的类的USB存储设备的序列号(信息经过过滤以仅显示USB设备,但可以删除该过滤器)

 私有无效DeviceChangedEvent(对象发送者,EventArrivedEventArgs e)
{
使用(ManagementBaseObject moBase =(ManagementBaseObject)e)。 NewEvent.Properties [ TargetInstance]。Value)
{
string oInterfaceType = moBase?.Properties [ InterfaceType]] .. Value.ToString();
string devicePNPId = moBase?.Properties [ PNPDeviceID] ?. Value.ToString();
string deviceDescription = moBase?.Properties [ Caption] ?. Value.ToString();
string eventMessage = $ {oInterfaceType}:{deviceDescription};

开关(e.NewEvent.ClassPath.ClassName)
{
case __InstanceDeletionEvent:
eventMessage + =移除;
this.BeginInvoke(new MethodInvoker(()=> {this.UpdateUI(eventMessage);})));
休息时间;
case __InstanceCreationEvent:
eventMessage + =已插入;
this.BeginInvoke(new MethodInvoker(()=> {this.UpdateUI(eventMessage);})));
休息时间;
case __InstanceModificationEvent:
默认值:
Console.WriteLine(e.NewEvent.ClassPath.ClassName);
休息时间;
}
}
}


private void UpdateUI(string message)
{
//用以下命令更新UI控件事件提供的信息
}


I can catch when usb device is connected with Win32_DeviceChangeEvent

but there are only 3 properties allowed to view

class Win32_DeviceChangeEvent : __ExtrinsicEvent
{
  uint8  SECURITY_DESCRIPTOR[];
  uint64 TIME_CREATED;
  uint16 EventType;
};

But i don't understand how to get all info about this device. Specifically, its port and hub, VirtualHubAdress Name and etc.

public enum EventType
{
    Inserted = 2,
    Removed = 3
}

public static void RegisterUsbDeviceNotification()
{
    var watcher = new ManagementEventWatcher();
    var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");
    //watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
    watcher.EventArrived += (s, e) =>
    {
        //here is im need to get info about this device

        EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));
    };

    watcher.Query = query;
    watcher.Start();
}

maybe i can do it with using smth like this

[DllImport("UseFull.dll")] 
private IntpPtr GetAllinfo(params);

解决方案

The Win32_DeviceChangeEvent reports just the type of event that occurred and the Time of the event (uint64, representing 100-nanosecond intervals after January 1, 1601, UTC). No that much useful if you also want to know what arrived or was removed.

I suggest to use instead the WqlEventQuery class, setting its EventClassName to [__InstanceOperationEvent][4].
This system class provides a TargetInstance property the can be cast to a ManagementBaseObject, the full management object that also provides base information on the Device that generated the event.
Among these information (which include the friendly name of the Device), the PNPDeviceID, which can be used to build other queries to further inspect the Device referenced.

The WqlEventQuery's Condition property can be set here to TargetInstance ISA 'Win32_DiskDrive'.
It can be set to any other Win32_ class of interest.

Setup the event listener (local machine):
(The event handler is called DeviceChangedEvent)

WqlEventQuery query = new WqlEventQuery() {
    EventClassName = "__InstanceOperationEvent",
    WithinInterval = new TimeSpan(0, 0, 3),
    Condition = @"TargetInstance ISA 'Win32_DiskDrive'"
};

ManagementScope scope = new ManagementScope("root\\CIMV2");
using (ManagementEventWatcher moWatcher = new ManagementEventWatcher(scope, query))
{
    moWatcher.Options.Timeout = ManagementOptions.InfiniteTimeout;
    moWatcher.EventArrived += new EventArrivedEventHandler(DeviceChangedEvent);
    moWatcher.Start();
}

The event handler receives, in e.NewEvent.Properties["TargetInstance"], the Management Object representing a [Win32_DiskDrive][7] class.
See the Docs about the properties directly available here.

The __InstanceOperationEvent derived classes of interest, reported by the e.NewEvent.ClassPath.ClassName, can be:

__InstanceCreationEvent: A new Device arrival has been detected.
__InstanceDeletionEvent: A Device removal has been detected.
__InstanceModificationEvent: An existing device has been modified in some way.

Note that the event is raised in a secondary thread, we need to BeginInvoke the UI thread to update the UI with the new informations.

See here: Get serial number of usb storage device for a class that provides most of the information available about a device (the informations are filtered to show USB devices only, but the filter can be removed).

private void DeviceChangedEvent(object sender, EventArrivedEventArgs e)
{
    using (ManagementBaseObject moBase = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)
    {
        string oInterfaceType = moBase?.Properties["InterfaceType"]?.Value.ToString();
        string devicePNPId = moBase?.Properties["PNPDeviceID"]?.Value.ToString();
        string deviceDescription = moBase?.Properties["Caption"]?.Value.ToString();
        string eventMessage = $"{oInterfaceType}: {deviceDescription} ";

        switch (e.NewEvent.ClassPath.ClassName)
        {
            case "__InstanceDeletionEvent":
                eventMessage += " removed";
                this.BeginInvoke(new MethodInvoker(() => { this.UpdateUI(eventMessage); }));
                break;
            case "__InstanceCreationEvent":
                eventMessage += "inserted";
                this.BeginInvoke(new MethodInvoker(() => { this.UpdateUI(eventMessage); }));
                break;
            case "__InstanceModificationEvent":
            default:
                Console.WriteLine(e.NewEvent.ClassPath.ClassName);
                break;
        }
    }
}


private void UpdateUI(string message)
{
   //Update the UI controls with information provided by the event
}

这篇关于如何获取有关最近连接的USB设备的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆