我需要對所有驅動器進行檢查,看看是否有任何VID/PID匹配特定的驅動器,如果有,我需要獲取該驅動器的驅動器號。 謝謝大家!如何從C#中的USB閃存驅動器獲取VID/PID?
7
A
回答
1
WMI應該能夠處理這個...
您必須添加一個引用到System.Management DLL,你將需要有: 「使用System.Management;」行...查看鏈接底部截圖,更透徹的解釋...
using System.Management;
// Get all the disk drives
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
// Loop through each object (disk) retrieved by WMI
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Add the HDD to the list (use the Model field as the item's caption)
cmbHdd.Items.Add(moDisk["Model"].ToString());
}
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
{
// Get all the disk drives from WMI that match the Model name selected in the ComboBox
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE Model = '" + cmbHdd.SelectedItem + "'");
// Loop through the drives retrieved, although it should normally be only one loop going on here
foreach (ManagementObject moDisk in mosDisks.Get())
{
// Set all the fields to the appropriate values
lblType.Text = "Type: " + moDisk["MediaType"].ToString();
lblModel.Text = "Model: " + moDisk["Model"].ToString();
lblSerial.Text = "Serial: " + moDisk["SerialNumber"].ToString();
lblInterface.Text = "Interface: " + moDisk["InterfaceType"].ToString();
// The capacity in gigabytes is easily calculated
lblCapacity.Text = "Capacity: " + moDisk["Size"].ToString() + " bytes (" + Math.Round(((((double)Convert.ToDouble(moDisk["Size"])/1024)/1024)/1024), 2) + " GB)";
lblPartitions.Text = "Partitions: " + moDisk["Partitions"].ToString();
lblSignature.Text = "Signature: " + moDisk["Signature"].ToString();
lblFirmware.Text = "Firmware: " + moDisk["FirmwareRevision"].ToString();
lblCylinders.Text = "Cylinders: " + moDisk["TotalCylinders"].ToString();
lblSectors.Text = "Sectors: " + moDisk["TotalSectors"].ToString();
lblHeads.Text = "Heads: " + moDisk["TotalHeads"].ToString();
lblTracks.Text = "Tracks: " + moDisk["TotalTracks"].ToString();
lblBytesPerSect.Text = "Bytes per Sector: " + moDisk["BytesPerSector"].ToString();
lblSectorsPerTrack.Text = "Sectors per Track: " + moDisk["SectorsPerTrack"].ToString();
lblTracksPerCyl.Text = "Tracks per Cylinder: " + moDisk["TracksPerCylinder"].ToString();
}
}
從MSDN爲CIM_DiskDrive的win32類具有下列參數:
*看起來好像「的DeviceID」是什麼你想...
class Win32_DiskDrive : CIM_DiskDrive
{
uint16 Availability;
uint32 BytesPerSector;
uint16 Capabilities[];
string CapabilityDescriptions[];
string Caption;
string CompressionMethod;
uint32 ConfigManagerErrorCode;
boolean ConfigManagerUserConfig;
string CreationClassName;
uint64 DefaultBlockSize;
string Description;
string DeviceID;
boolean ErrorCleared;
string ErrorDescription;
string ErrorMethodology;
string FirmwareRevision;
uint32 Index;
datetime InstallDate;
string InterfaceType;
uint32 LastErrorCode;
string Manufacturer;
uint64 MaxBlockSize;
uint64 MaxMediaSize;
boolean MediaLoaded;
string MediaType;
uint64 MinBlockSize;
string Model;
string Name;
boolean NeedsCleaning;
uint32 NumberOfMediaSupported;
uint32 Partitions;
string PNPDeviceID;
uint16 PowerManagementCapabilities[];
boolean PowerManagementSupported;
uint32 SCSIBus;
uint16 SCSILogicalUnit;
uint16 SCSIPort;
uint16 SCSITargetId;
uint32 SectorsPerTrack;
string SerialNumber;
uint32 Signature;
uint64 Size;
string Status;
uint16 StatusInfo;
string SystemCreationClassName;
string SystemName;
uint64 TotalCylinders;
uint32 TotalHeads;
uint64 TotalSectors;
uint64 TotalTracks;
uint32 TracksPerCylinder;
};
頂部的代號取自:
http://www.geekpedia.com/tutorial233_Getting-Disk-Drive-Information-using-WMI-and-Csharp.html
1
如果您只需檢查設備何時連接,問題就簡單多了。您需要檢查DBT_DEVICEARRIVAL
事件。如果您正在創建Windows Forms應用程序,則可以通過執行IMessageFilter
接口並將其傳遞給Application
中的AddMessageFiler
函數來完成。如果您不使用Forms應用程序,則需要從NativeWindow
派生一個類並覆蓋WndProc。記住呼叫CreateHandle,這樣它會被添加到Windows消息隊列中。
一旦你有辦法接收DBT_DEVICEARRIVAL
你需要解析它。 (下面是不是寫在一個IDE所以它沒有經過測試)
// Constants from from Dbt.h
const int WM_DEVICECHANGE = 0x219;
const int DBT_DEVICEARRIVAL = 0x8000;
const uint DBT_DEVTYP_DEVICEINTERFACE = 0x05;
const Guid GUID_DEVINTERFACE_USB_DEVICE = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED");
bool PreFilterMessage(ref Message m)
{
if(m.Msg == case WM_DEVICECHANGE && m.WParam == DBT_DEVICEARRIVAL)
var broadcast = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(pnt, typeof(DEV_BROADCAST_HDR));
if(broadcast.dbch_DeviceType == DBT_DEVTYP_DEVICEINTERFACE)
{
var devInterface = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(pnt, typeof(DEV_BROADCAST_DEVICEINTERFACE));
if(devInterface.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE)
{
// devInterface.dbcc_name will contain the VID and PID for example:
// \\?\USB#Vid_067b&Pid_2517#6&12115ad4&2&1#{GUID}
DoSomthingSpecial(devInterface.dbcc_name);
}
}
}
return false;
}
[StructLayout(LayoutKind.Sequential)]
struct DEV_BROADCAST_HDR {
public uint dbch_Size;
public uint dbch_DeviceType;
public uint dbch_Reserved;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct DEV_BROADCAST_DEVICEINTERFACE
{
public int dbcc_size;
public int dbcc_devicetype;
public int dbcc_reserved;
public Guid dbcc_classguid;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=255)]
public string dbcc_name;
}
如果您需要枚舉已連接我只想建議使用WMI method所有設備。如果你想知道如何在沒有WMI的情況下執行此操作,請查看Windows Driver Development Kit中的代碼USBView,它可以幫助你開始。
1
public static bool GetDriveVidPid(string szDriveName, ref ushort wVID, ref ushort wPID)
{
bool bResult = false;
string szSerialNumberDevice = null;
ManagementObject oLogicalDisk = new ManagementObject("Win32_LogicalDisk.DeviceID='" + szDriveName.TrimEnd('\\') + "'");
foreach(ManagementObject oDiskPartition in oLogicalDisk.GetRelated("Win32_DiskPartition"))
{
foreach(ManagementObject oDiskDrive in oDiskPartition.GetRelated("Win32_DiskDrive"))
{
string szPNPDeviceID = oDiskDrive["PNPDeviceID"].ToString();
if(!szPNPDeviceID.StartsWith("USBSTOR"))
throw new Exception(szDriveName + " ist kein USB-Laufwerk.");
string[] aszToken = szPNPDeviceID.Split(new char[] { '\\', '&' });
szSerialNumberDevice = aszToken[aszToken.Length - 2];
}
}
if(null != szSerialNumberDevice)
{
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(@"root\CIMV2", "Select * from Win32_USBHub");
foreach(ManagementObject oResult in oSearcher.Get())
{
object oValue = oResult["DeviceID"];
if(oValue == null)
continue;
string szDeviceID = oValue.ToString();
string[] aszToken = szDeviceID.Split(new char[] { '\\' });
if(szSerialNumberDevice != aszToken[aszToken.Length - 1])
continue;
int nTemp = szDeviceID.IndexOf(@"VID_");
if(0 > nTemp)
continue;
nTemp += 4;
wVID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
nTemp += 4;
nTemp = szDeviceID.IndexOf(@"PID_", nTemp);
if(0 > nTemp)
continue;
nTemp += 4;
wPID = ushort.Parse(szDeviceID.Substring(nTemp, 4), System.Globalization.NumberStyles.AllowHexSpecifier);
bResult = true;
break;
}
}
return bResult;
}
相關問題
- 1. 如何檢測USB閃存驅動器的盤符USB閃存驅動器的
- 2. 從USB閃存驅動器運行Tomcat
- 3. 如何從USB閃存驅動器讀取數據?
- 4. Python:獲取USB閃存驅動器設備的名稱[windows]
- 5. 如何從USB閃存驅動器運行Android工作室ubuntu
- 6. USB閃存驅動器問題
- 7. 用PC模擬USB閃存驅動器
- 8. USB閃存驅動器分區
- 9. 在Windows中編程區分USB軟盤驅動器和USB閃存驅動器
- 10. 如何獲取USB閃存驅動器的製造商序列號?
- 11. 如何在USB閃存驅動器中製作安裝程序?
- 12. 如何在C中找到安裝的USB閃存驅動器的大小?
- 13. Javascript:我如何從USB閃存驅動器讀取文件和文件夾
- 14. 我們可以從USB閃存驅動器獲取VID和PID嗎?
- 15. 在Windows上區分USB閃存驅動器和USB硬盤驅動器
- 16. 如何使用PowerShell查找USB閃存驅動器的路徑
- 17. 如何開發一個加密的USB閃存驅動器
- 18. 從USB閃存驅動器自動運行程序
- 19. 錯誤分區和格式化USB閃存驅動器在C + +
- 20. C#檢查存在的USB驅動器
- 21. QNX 6.6 Windows主機 - USB閃存驅動器中的閃存圖像
- 22. 如何解決從USB閃存驅動器運行wampserver的問題?
- 23. USB驅動器LED閃光燈
- 24. 在USB閃存驅動器連接時在Windows中運行vbscript
- 25. 區分數據卡和筆式驅動器或USB閃存驅動器
- 26. 獲取閃存驅動器的讀取和寫入速度
- 27. 如何從usb驅動器運行nodejs?
- 28. Android:檢測插入的USB閃存驅動器
- 29. 閱讀像USB閃存驅動器的iPad/iPhone磁盤
- 30. Android USB OTG讀取USB驅動器
這是OP問題更好的解決方案,因爲WMI是完全矯枉過正的。 – 2015-04-14 00:05:22