Detect iPhone using WMI in C#

2019-04-15 08:05发布

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?

标签: c# iphone wmi
1条回答
The star\"
2楼-- · 2019-04-15 08:45

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;
}
查看更多
登录 后发表回答