-
-
Save SpacePurr/c35aa79e8d702b5d639cef05f05f188c to your computer and use it in GitHub Desktop.
UsbListener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Файл содержит в себе 3 класса | |
// 1. UsbListener | |
// 2. DeviceChangedEventArgs | |
// 3. EventType | |
//EventType - набор типов событий. | |
//DeviceChangedEventArgs - класс, содержащий данные события. Наследуется от EventArgs и | |
// содержит в себе информацию класса EventArrivedEventArgs в более удобном виде. | |
//UsbListener - класс, содержащий в себе все настройки и обработку событий подключения/отключения USB устройств. | |
//В конструкторе класса можно передать DeviceId устройства, по которому будет фильтроваться обработка событий. | |
//Основная часть обработки событий происходит как раз в классе UsbListener, но для дополнительных действий | |
// созданы публичные делегаты: | |
// 1. OnInsertDevice - делегат, срабатывающий при подключении устрйоства. | |
// 2. OnDeleteDevice - делегат, срабатывающий при отключении устройства. | |
// 3. OnGetUsbDevices - делегат для вывода списка всех USB устройств. | |
//Пример работы с библиотекой приведен тут: | |
//https://gist.github.com/SpacePurr/f92b17b415c176474fd177ea41158b9e | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Management; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace TestConsole | |
{ | |
class UsbListener | |
{ | |
public string DeviceId { get; set; } | |
private readonly string inQuery; | |
private readonly string outQuery; | |
private readonly ManagementEventWatcher inWatcher; | |
private readonly ManagementEventWatcher outWatcher; | |
public event Action<object, DeviceChangedEventArgs> OnInsertDevice; | |
public event Action<object, DeviceChangedEventArgs> OnDeleteDevice; | |
public static event Action<ManagementObjectCollection> OnGetUsbDevices; | |
public UsbListener() | |
{ | |
inQuery = "SELECT * FROM __InstanceCreationEvent " + | |
"WITHIN 2 " + | |
"WHERE TargetInstance ISA 'Win32_PnPEntity'"; | |
inWatcher = new ManagementEventWatcher(inQuery); | |
inWatcher.EventArrived += InWatcher_EventArrived; | |
outQuery = "SELECT TargetInstance " + | |
"FROM __InstanceDeletionEvent " + | |
"WITHIN 2 " + | |
"WHERE TargetInstance ISA 'Win32_PnPEntity' "; | |
outWatcher = new ManagementEventWatcher(outQuery); | |
outWatcher.EventArrived += OutWatcher_EventArrived; | |
} | |
public UsbListener(string deviceId) : this() | |
{ | |
DeviceId = deviceId; | |
} | |
#region Events | |
private void InWatcher_EventArrived(object sender, EventArrivedEventArgs e) | |
{ | |
ManagementBaseObject deviceManager = (ManagementBaseObject)e.NewEvent["TargetInstance"]; | |
var deviceEventArgs = new DeviceChangedEventArgs(deviceManager, EventType.Insert) | |
{ | |
DeviceId = deviceManager["DeviceID"]?.ToString(), | |
}; | |
if (!string.IsNullOrEmpty(DeviceId)) | |
{ | |
if(DeviceId == deviceEventArgs.DeviceId) | |
{ | |
OnInsertDevice?.Invoke(sender, deviceEventArgs); | |
} | |
return; | |
} | |
OnInsertDevice?.Invoke(sender, deviceEventArgs); | |
} | |
private void OutWatcher_EventArrived(object sender, EventArrivedEventArgs e) | |
{ | |
ManagementBaseObject deviceManager = (ManagementBaseObject)e.NewEvent["TargetInstance"]; | |
var deviceEventArgs = new DeviceChangedEventArgs(deviceManager, EventType.Delete) | |
{ | |
DeviceId = deviceManager["DeviceID"]?.ToString() | |
}; | |
if (!string.IsNullOrEmpty(DeviceId)) | |
{ | |
if (DeviceId == deviceEventArgs.DeviceId) | |
{ | |
OnDeleteDevice?.Invoke(sender, deviceEventArgs); | |
} | |
return; | |
} | |
OnDeleteDevice?.Invoke(sender, deviceEventArgs); | |
} | |
#endregion | |
public void Start() | |
{ | |
inWatcher.Start(); | |
outWatcher.Start(); | |
} | |
public void Stop() | |
{ | |
inWatcher.Stop(); | |
outWatcher.Stop(); | |
inWatcher.Dispose(); | |
outWatcher.Dispose(); | |
} | |
#region GetMethods | |
public static void GetUSBDevices() | |
{ | |
using (var searcher = new ManagementObjectSearcher(@"Select * From Win32_USBHub")) | |
{ | |
ManagementObjectCollection collection = searcher.Get(); | |
OnGetUsbDevices?.Invoke(collection); | |
collection.Dispose(); | |
} | |
} | |
#endregion | |
} | |
class DeviceChangedEventArgs : EventArgs | |
{ | |
private readonly EventType type; | |
public ManagementBaseObject DeviceManager { get; set; } | |
public string DeviceId { get; set; } | |
public string Type { get => type == EventType.Insert ? "Подключение устройства" : "Отключение устройства"; } | |
public DeviceChangedEventArgs(ManagementBaseObject deviceManager, EventType type) | |
{ | |
DeviceManager = deviceManager; | |
this.type = type; | |
} | |
} | |
enum EventType | |
{ | |
Insert, Delete | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment