gpt4 book ai didi

c# - 如何在 C# winform 中明智地检测 USB 设备类别的插入?

转载 作者:行者123 更新时间:2023-11-30 16:52:31 27 4
gpt4 key购买 nike

USB thumb drives
USB harddisks
USB DVD writer
USB Bluetooth devices
USB headsets
usb mouse
USB keyboard
USB webcams / cameras

只想使用事件处理程序检测任何类型的 USB 设备...将不胜感激任何帮助...

WqlEventQuery q_creation = new WqlEventQuery();
private void Form2_Load(object sender, EventArgs e)
{



q_creation.EventClassName = "__InstanceCreationEvent";
q_creation.WithinInterval = new TimeSpan(0, 0, 2); //How often do you want to check it? 2Sec.
q_creation.Condition = @"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'";
var mwe_creation = new ManagementEventWatcher(q_creation);
mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
mwe_creation.Start(); // Start listen for events
}
/// <summary>
/// Callback event
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
{
MessageBox.Show("Device Connected");
}

这是我试过的代码。

最佳答案

我正在为你粘贴我的整个类(class),按原样使用(连接底部的事件以检测或移除 USB):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BlueMercs.Core.Services.WMI
{

public class EventUsbMonitorEvent : EventArgs
{
public string Model { get; set; }
public string Drive { get; set; }
}

public class UsbMonitor
{
private const string _queryForEvents = @"SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_DiskDrive'";
private string _queryDiskPartitionDevice = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"{0}\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
private string _queryDiskLogicalPartition = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"{0}\"} WHERE AssocClass = Win32_LogicalDiskToPartition";



private readonly ManagementEventWatcher _watcher;
private Thread _thread;

public UsbMonitor()
{
_watcher = new ManagementEventWatcher();
var query = new WqlEventQuery(_queryForEvents);
_watcher.EventArrived += Watcher_EventArrived;
_watcher.Query = query;
}

public void Start()
{
_watcher.Start();
_thread = new Thread(Listen);
_thread.Start();
}

public void Stop()
{
try { _thread.Abort(); } catch { } //suppress thread abort exception
_watcher.Stop();
}

private void Listen()
{
_watcher.WaitForNextEvent();
Listen();
}

private string GetDriveLetterFromDisk(string name)
{
name = name.Replace(@"\", @"\\");
var driveLetter = string.Empty;
var qryPartition = new ObjectQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID=\"" + name + "\"} WHERE AssocClass = Win32_DiskDriveToDiskPartition"); //string.Format(_queryDiskPartitionDevice, name));
var partition = new ManagementObjectSearcher(qryPartition);

foreach (var result in partition.Get())
{
//var qryLogicalDisk = new ObjectQuery(string.Format(_queryDiskLogicalPartition, result["DeviceID"]));
var logicalDisk = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID=\"" + result["DeviceID"] + "\"} WHERE AssocClass = Win32_LogicalDiskToPartition"); //qryLogicalDisk);
driveLetter = logicalDisk.Get().Cast<ManagementBaseObject>().Aggregate(driveLetter, (current, x) => current + (x["Name"] + ","));
}

return driveLetter.Trim(',');
}

private void Watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject targetInstance;

switch (e.NewEvent.ClassPath.ClassName)
{
case "__InstanceCreationEvent":
targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if (targetInstance["InterfaceType"].ToString() == "USB")
{
var driveName = targetInstance["Caption"].ToString();
var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
if (OnExternalUsbDetected != null)
OnExternalUsbDetected(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
}
break;

case "__InstanceDeletionEvent":
targetInstance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
if (targetInstance["InterfaceType"].ToString() == "USB")
{
var driveName = targetInstance["Caption"].ToString();
var driveLetter = GetDriveLetterFromDisk(targetInstance["Name"].ToString());
if (OnExternalUsbRemoved != null)
OnExternalUsbRemoved(this, new EventUsbMonitorEvent { Model = driveName, Drive = driveLetter });
}
break;
}
}

public event EventHandler<EventUsbMonitorEvent> OnExternalUsbDetected;
public event EventHandler<EventUsbMonitorEvent> OnExternalUsbRemoved;
}
}

关于c# - 如何在 C# winform 中明智地检测 USB 设备类别的插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com