7

USB の取り付け/取り外しの際に、固有の USB ID (ボリュームのシリアル番号ではありません) を取得する必要があります。ただし、どの場合でも「PNPDeviceID」は常に空です。私が使用したコードは次のとおりです。

static void Main(string[] args)
{ 
    const string QUERY = @"select * from __InstanceOperationEvent within 1 where TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveType=2)"; 
    Program p = new Program(); 
    ManagementEventWatcher w = new ManagementEventWatcher(new WqlEventQuery(QUERY));
    w.EventArrived += new EventArrivedEventHandler(p.OnWMIEvent); 
    w.Start();
    Console.ReadKey();
    w.Stop();
}

public void OnWMIEvent(object sender, EventArrivedEventArgs e)
{
    PropertyData p = e.NewEvent.Properties["TargetInstance"]; 
    if (p != null) 
    {
        ManagementBaseObject mbo = p.Value as ManagementBaseObject;
        PropertyData deviceid = mbo.Properties["DeviceID"]; 
        PropertyData drivetype = mbo.Properties["DriveType"];
        PropertyData driveSerial = mbo.Properties["VolumeSerialNumber"];
        PropertyData driveGUID = mbo.Properties["PNPDeviceID"];

        Console.WriteLine("{0}-{1}", "DeviceID",deviceid.Value); 
        Console.WriteLine("{0}-{1}", "DriveType",drivetype.Value);
        Console.WriteLine("{0}-{1}", "DriveSerial", driveSerial.Value);
        Console.WriteLine("{0}-{1}", "driveGUID", driveGUID.Value);
        Console.WriteLine();
    }
} 

出典:これ

次のコードで UNIQUE USB ID を取得できます。

ManagementObjectSearcher theSearcher = 
    new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType='USB'");

foreach(ManagementObject currentObject in theSearcher.Get())
{
    Console.WriteLine("{0}-{1}", "PNPDeviceID", currentObject.Properties["PNPDeviceID"].Value);            
}

USBスティックを挿入/削除するときに、それらを組み合わせてPNPDeviceId(USB GUID)を受け取る方法を教えてください

4

1 に答える 1

2

Win32_LogicalDiskクラスを直接クエリしてPNPDeviceIDプロパティの値を取得しない場合は、wmi イベント内でこのクラスを使用しても値を取得できません。代わりに、組み込みイベントWin32_DiskDriveでクラスを使用できます。__InstanceOperationEvent

Select * From __InstanceOperationEvent Within 1 Where TargetInstance ISA 'Win32_DiskDrive' and TargetInstance.InterfaceType='USB'
于 2011-06-07T18:40:02.363 に答える