1

我制作了一个控制台应用程序,它检测所有类型的 USB 设备的插件和插件事件。但我想在其中进行一些过滤,就像我只想检测网络摄像头一样。这是通过使用 GUID 类完成的。网络摄像头的类是带有 GUID“{6bdd1fc5-810f-11d0-bec7-08002be2092f}”的“图像”类。问题是这个“图像”类也用于扫描仪,我不想检测扫描仪。代码是下面给出:

static void Main(string[] args)
    {
        WqlEventQuery weqQuery = new WqlEventQuery();
        weqQuery.EventClassName = "__InstanceOperationEvent";
        weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
        weqQuery.Condition = @"TargetInstance ISA 'Win32_PnPEntity'";

        ManagementEventWatcher m_mewWatcher = new ManagementEventWatcher(weqQuery);
        m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);

        m_mewWatcher.Start();
        Console.ReadLine();
    }

    static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
    {
        bool bUSBEvent = false;
        string deviceCaption = "";
        string deviceType = "";

        foreach (PropertyData pdData in e.NewEvent.Properties)
        {
            try
            {
                ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
                if (mbo != null)
                {

                    foreach (PropertyData pdDataSub in mbo.Properties)
                    {

                        Console.WriteLine(pdDataSub.Name + " = " + pdDataSub.Value);
                        if (pdDataSub.Name == "Caption")
                        {
                            deviceCaption = pdDataSub.Value.ToString();
                        }
                        if (pdDataSub.Name == "ClassGuid" && pdDataSub.Value.ToString() == "{6bdd1fc5-810f-11d0-bec7-08002be2092f}")
                        {
                            bUSBEvent = true;
                            deviceType = "Image";
                        }
                    }
                    if (bUSBEvent)
                    {
                        if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
                        {
                            Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged in at " + DateTime.Now.ToString());
                        }
                        else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
                        {
                            Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged out at " + DateTime.Now.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
    }

如需参考,请查看此链接

4

1 回答 1

1

我等了,但没有人回答这个问题,所以在看到ManagementBaseObject的所有属性后,我发现有一个名为Service的属性对于扫描仪来说是不同的。在扫描仪中,Service 属性的值是usbscan,而在相机中则是 usbvideo。例如。你可以做这样的事情

if (mbo.Properties["Service"].Value.ToString() == "usbscan")
{
//then it means it is a scanner
}
else
{
//then it means it is a camera
}

注意:主要问题是我们如何区分扫描仪和网络摄像头,因为它们都使用相同的 GUID。

于 2014-02-17T07:32:48.860 回答