开发者

Detect iPhone using WMI in C#

开发者 https://www.devze.com 2023-02-06 09:34 出处:网络
I\'m using the following code to detect a USB device when it\'s connected to the computer: private ManagementEventWatcher m_watcher;

I'm using the following code to detect a USB device when it's connected to the computer:

private ManagementEventWatcher m_watcher;
try
    {
        string queryString =
          "SELECT * " +
          " FROM __InstanceCreationEvent " +
          " WITHIN " + pollingInterval +
     开发者_运维技巧     " WHERE TargetInstance ISA 'Win32_USBHub'";

        EventQuery processQuery = new EventQuery(queryString);
        ManagementScope scope = new ManagementScope("root\\CIMV2");
        scope.Options.EnablePrivileges = true;

        m_watcher = new ManagementEventWatcher(scope, processQuery);
        m_watcher.EventArrived += new System.Management.EventArrivedEventHandler(EventArrived);
        m_watcher.Start();
    }

private void EventArrived(object sender, EventArrivedEventArgs e)
{
    var instance = ((PropertyData)(e.NewEvent.Properties["TargetInstance"]));
    var obj = (ManagementBaseObject)instance.Value;
    var args = new InsertEventArgs();

    var description = (string)obj.Properties["Description"].Value;
    var deviceId = (string) obj.Properties["DeviceID"].Value;
    var status = (string) obj.Properties["Status"].Value;

This works correctly when i attach a usb-key and a Samsung mobile phone. When I attach an iPhone, the EventArrived function is never hit. Am I using a wrong event? What am i doing wrong?


Try this code:

var queryStr = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'";

var watcher = new ManagementEventWatcher(queryStr);
watcher.EventArrived += DeviceChangeEventReceived;
watcher.Start();

Event handler:

private static void DeviceChangeEventReceived(object sender, EventArrivedEventArgs e)
{
    var instance = ((PropertyData)(e.NewEvent.Properties["TargetInstance"]));
    var obj = (ManagementBaseObject)instance.Value;

    var description = (string)obj.Properties["Description"].Value;
    var deviceId = (string)obj.Properties["DeviceID"].Value;
    var status = (string)obj.Properties["Status"].Value;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消