<p>Using .Net (C#), how can you work with USB devices? </p>

<p>How can you detect USB events (connections/disconnections) and how do you communicate with devices (read/write).</p>

<p>Is there a native .Net solution to do this?</p>

[{'answer_id': 68805, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 0, 'selected': False, 'text': '<p>Most USB chipsets come with drivers.  <a href="https://www.silabs.com/products/mcu/usb/Pages/default.aspx" rel="nofollow noreferrer">Silicon Labs</a> has one.</p>\n'}, {'answer_id': 68827, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 6, 'selected': True, 'text': '<p>There is no <em>native</em> (e.g., System libraries) solution for this. That\'s the reason why <a href="http://www.icsharpcode.net/OpenSource/SharpUSBLib/" rel="nofollow noreferrer">SharpUSBLib</a> exists as mentioned by <a href="https://stackoverflow.com/questions/68749/working-with-usb-devices-in-net#68777">moobaa</a>.</p>\n\n<p>If you wish to roll your own handler for USB devices, you can check out the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport" rel="nofollow noreferrer">SerialPort class of System.IO.Ports</a>.</p>\n'}, {'answer_id': 70370, 'author': 'Ilya', 'author_id': 6807, 'author_profile': 'https://Stackoverflow.com/users/6807', 'pm_score': 1, 'selected': False, 'text': '<p>There is a generic toolkit <a href="http://www.jungo.com/st/windriver_usb_pci_driver_development_software.html#" rel="nofollow noreferrer">WinDriver</a> for writing USB Drivers in user mode that support #.NET as well </p>\n'}, {'answer_id': 2651624, 'author': 'Sofox', 'author_id': 232147, 'author_profile': 'https://Stackoverflow.com/users/232147', 'pm_score': 5, 'selected': False, 'text': '<p>I\'ve tried using SharpUSBLib and it screwed up my computer (needed a system restore). Happened to a coworker on the same project too.</p>\n\n<p>I\'ve found an alternative in LibUSBDotNet: <a href="http://sourceforge.net/projects/libusbdotnet" rel="noreferrer">http://sourceforge.net/projects/libusbdotnet</a>\nHavn\'t used it much yet but seems good and recently updated (unlike Sharp).</p>\n\n<p>EDIT: As of mid-February 2017, LibUSBDotNet was updated about 2 weeks ago. Meanwhile SharpUSBLib has not been updated since 2004.</p>\n'}, {'answer_id': 5235377, 'author': 'James Crowley', 'author_id': 33682, 'author_profile': 'https://Stackoverflow.com/users/33682', 'pm_score': 2, 'selected': False, 'text': '<p>There\'s a tutorial on getting the SharpUSBLib library and HID drivers working with C# here: </p>\n\n<p><a href="http://www.developerfusion.com/article/84338/making-usb-c-friendly/" rel="nofollow">http://www.developerfusion.com/article/84338/making-usb-c-friendly/</a></p>\n'}, {'answer_id': 12027784, 'author': 'Brad Bruce', 'author_id': 5008, 'author_profile': 'https://Stackoverflow.com/users/5008', 'pm_score': 0, 'selected': False, 'text': '<p>I\'ve gotten an interface to a <a href="http://www.pjrc.com/teensy/index.html" rel="nofollow">Teensy</a> working quite well, using <a href="http://www.codeproject.com/Articles/18099/A-USB-HID-Component-for-C" rel="nofollow">this article</a></p>\n'}, {'answer_id': 12682958, 'author': 'Alex Klaus', 'author_id': 968003, 'author_profile': 'https://Stackoverflow.com/users/968003', 'pm_score': 3, 'selected': False, 'text': '<p>I\'d recommend <a href="https://www.nuget.org/packages/LibUsbDotNet/" rel="nofollow noreferrer">LibUSBDotNet</a>, the library I have been using for 2 years.\nIf you have to work with an USB device (send requests, process responses), this library was the best solution I could find.</p>\n<p><strong>Pros:</strong></p>\n<ul>\n<li>Has all methods you need to work in synch or asynch mode.</li>\n<li>Source code provided</li>\n<li>Enough samples to start using it straight away.</li>\n</ul>\n<p><strong>Cons:</strong></p>\n<ul>\n<li>Poor documentation (it\'s common problem for open source projects). Basically, you can find just common description of methods in the CHM help file and that\'s it.\nBut I still find provided samples and source code is enough for coding.\nJust sometimes I see a strange behaviour and want to know why it was implemented in this way and can\'t get even a hint...</li>\n<li>Seems unsupported any more. Last version was issued in Oct 2010. And it\'s hard to get answers sometimes.</li>\n</ul>\n'}, {'answer_id': 13829628, 'author': 'Syn', 'author_id': 1895588, 'author_profile': 'https://Stackoverflow.com/users/1895588', 'pm_score': 4, 'selected': False, 'text': '<p>I used the following code to detect when USB devices were plugged and unplugged from my computer:</p>\n\n<pre><code>class USBControl : IDisposable\n    {\n        // used for monitoring plugging and unplugging of USB devices.\n        private ManagementEventWatcher watcherAttach;\n        private ManagementEventWatcher watcherRemove;\n\n        public USBControl()\n        {\n            // Add USB plugged event watching\n            watcherAttach = new ManagementEventWatcher();\n            //var queryAttach = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");\n            watcherAttach.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);\n            watcherAttach.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2");\n            watcherAttach.Start();\n\n            // Add USB unplugged event watching\n            watcherRemove = new ManagementEventWatcher();\n            //var queryRemove = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");\n            watcherRemove.EventArrived += new EventArrivedEventHandler(watcher_EventRemoved);\n            watcherRemove.Query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3");\n            watcherRemove.Start();\n        }\n\n        /// &lt;summary&gt;\n        /// Used to dispose of the USB device watchers when the USBControl class is disposed of.\n        /// &lt;/summary&gt;\n        public void Dispose()\n        {\n            watcherAttach.Stop();\n            watcherRemove.Stop();\n            //Thread.Sleep(1000);\n            watcherAttach.Dispose();\n            watcherRemove.Dispose();\n            //Thread.Sleep(1000);\n        }\n\n        void watcher_EventArrived(object sender, EventArrivedEventArgs e)\n        {\n            Debug.WriteLine("watcher_EventArrived");\n        }\n\n        void watcher_EventRemoved(object sender, EventArrivedEventArgs e)\n        {\n            Debug.WriteLine("watcher_EventRemoved");\n        }\n\n        ~USBControl()\n        {\n            this.Dispose();\n        }\n\n\n    }\n</code></pre>\n\n<p>You have to make sure you call the Dispose() method when closing your application. Otherwise, you will receive a COM object error at runtime when closing.</p>\n'}, {'answer_id': 28775687, 'author': 'Pabinator', 'author_id': 1933253, 'author_profile': 'https://Stackoverflow.com/users/1933253', 'pm_score': 1, 'selected': False, 'text': '<p>If you have <strong>National Instruments</strong> software on you PC you can create a USB Driver using their <em>"NI-VISA Driver Wizard"</em>.  </p>\n\n<p>Steps to create the USB Driver: <a href="http://www.ni.com/tutorial/4478/en/" rel="nofollow noreferrer">http://www.ni.com/tutorial/4478/en/</a></p>\n\n<p>Once you created the driver you will be able to Write and Read bytes to any USB Device.</p>\n\n<p>Make sure the driver is seen by windows under Device Manager:</p>\n\n<p><img src="https://i.stack.imgur.com/ZJBla.png" alt="enter image description here"></p>\n\n<p>C# Code:</p>\n\n<pre><code>    using NationalInstruments.VisaNS;\n\n    #region UsbRaw\n    /// &lt;summary&gt;\n    /// Class to communicate with USB Devices using the UsbRaw Class of National Instruments\n    /// &lt;/summary&gt;\n    public class UsbRaw\n    {\n        private NationalInstruments.VisaNS.UsbRaw usbRaw;\n        private List&lt;byte&gt; DataReceived = new List&lt;byte&gt;();\n\n        /// &lt;summary&gt;\n        /// Initialize the USB Device to interact with\n        /// &lt;/summary&gt;\n        /// &lt;param name="ResourseName"&gt;In this format: "USB0::0x1448::0x8CA0::NI-VISA-30004::RAW".  Use the NI-VISA Driver Wizard from Start»All Programs»National Instruments»VISA»Driver Wizard to create the USB Driver for the device you need to talk to.&lt;/param&gt;\n        public UsbRaw(string ResourseName)\n        {\n            usbRaw = new NationalInstruments.VisaNS.UsbRaw(ResourseName, AccessModes.NoLock, 10000, false);\n            usbRaw.UsbInterrupt += new UsbRawInterruptEventHandler(OnUSBInterrupt);\n            usbRaw.EnableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);\n        }\n\n        /// &lt;summary&gt;\n        /// Clears a USB Device from any previous commands\n        /// &lt;/summary&gt;\n        public void Clear()\n        {\n            usbRaw.Clear();\n        }\n\n        /// &lt;summary&gt;\n        /// Writes Bytes to the USB Device\n        /// &lt;/summary&gt;\n        /// &lt;param name="EndPoint"&gt;USB Bulk Out Pipe attribute to send the data to.  For example: If you see on the Bus Hound sniffer tool that data is coming out from something like 28.4 (Device column), this means that the USB is using Endpoint 4 (Number after the dot)&lt;/param&gt;\n        /// &lt;param name="BytesToSend"&gt;Data to send to the USB device&lt;/param&gt;\n        public void Write(short EndPoint, byte[] BytesToSend)\n        {\n            usbRaw.BulkOutPipe = EndPoint;\n            usbRaw.Write(BytesToSend);       // Write to USB\n        }\n\n        /// &lt;summary&gt;\n        /// Reads bytes from a USB Device\n        /// &lt;/summary&gt;\n        /// &lt;returns&gt;Bytes Read&lt;/returns&gt;\n        public byte[] Read()\n        {\n            usbRaw.ReadByteArray();     // This fires the UsbRawInterruptEventHandler                \n\n            byte[] rxBytes = DataReceived.ToArray();      // Collects the data received\n\n            return rxBytes;\n        }\n\n        /// &lt;summary&gt;\n        /// This is used to get the data received by the USB device\n        /// &lt;/summary&gt;\n        /// &lt;param name="sender"&gt;&lt;/param&gt;\n        /// &lt;param name="e"&gt;&lt;/param&gt;\n        private void OnUSBInterrupt(object sender, UsbRawInterruptEventArgs e)\n        {\n            try\n            {\n                DataReceived.Clear();     // Clear previous data received\n                DataReceived.AddRange(e.DataBuffer);                    \n            }\n            catch (Exception exp)\n            {\n                string errorMsg = "Error: " + exp.Message;\n                DataReceived.AddRange(ASCIIEncoding.ASCII.GetBytes(errorMsg));\n            }\n        }\n\n        /// &lt;summary&gt;\n        /// Use this function to clean up the UsbRaw class\n        /// &lt;/summary&gt;\n        public void Dispose()\n        {\n            usbRaw.DisableEvent(UsbRawEventType.UsbInterrupt, EventMechanism.Handler);\n\n            if (usbRaw != null)\n            {\n                usbRaw.Dispose();\n            }              \n        }\n\n    }\n    #endregion UsbRaw\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>UsbRaw usbRaw = new UsbRaw("USB0::0x1448::0x8CA0::NI-VISA-30004::RAW");\n\nbyte[] sendData = new byte[] { 0x53, 0x4c, 0x56 };\nusbRaw.Write(4, sendData);      // Write bytes to the USB Device\nbyte[] readData = usbRaw.Read();   // Read bytes from the USB Device\n\nusbRaw.Dispose();\n</code></pre>\n\n<p>Hope this helps someone.</p>\n'}, {'answer_id': 50936836, 'author': 'Mike Lowery', 'author_id': 298511, 'author_profile': 'https://Stackoverflow.com/users/298511', 'pm_score': 0, 'selected': False, 'text': '<p>I tried several of these suggestions with no luck. I ended up writing a working solution using Java and the <a href="https://github.com/gary-rowe/hid4java" rel="nofollow noreferrer">hid4java</a> library. As a console app I can shell out to it from C# using <code>Process.Start()</code>, passing parameters as well as reading responses. This provides basic HID I/O but without connect/disconnect events. For that I\'d need to rewrite it to run as a daemon/service and use named pipes or some other server/client transport. For now, it\'s enough to get the job done since the hi4java library "just works".</p>\n'}, {'answer_id': 51854202, 'author': 'Christian Findlay', 'author_id': 1878141, 'author_profile': 'https://Stackoverflow.com/users/1878141', 'pm_score': 2, 'selected': False, 'text': '<p>USB devices usually fall in to two categories: Hid, and USB. A USB device may or may not be a Hid device and vice versa. Hid is usually a little easier to work with than direct USB. Different platforms have different APIs for dealing with both USB and Hid. </p>\n\n<p>Here is documentation for UWP:</p>\n\n<p>USB:\n<a href="https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/how-to-connect-to-a-usb-device--uwp-app-" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/windows-hardware/drivers/usbcon/how-to-connect-to-a-usb-device--uwp-app-</a></p>\n\n<p>Hid:\n<a href="https://learn.microsoft.com/en-us/uwp/api/windows.devices.humaninterfacedevice" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/uwp/api/windows.devices.humaninterfacedevice</a></p>\n\n<p>Here is the documentation for Android:\n<a href="https://developer.xamarin.com/api/namespace/Android.Hardware.Usb/" rel="nofollow noreferrer">https://developer.xamarin.com/api/namespace/Android.Hardware.Usb/</a></p>\n\n<p>Here are two classes for dealing with USB/Hid at the raw Windows API level:</p>\n\n<p><a href="https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Hid.Net/Windows/HidAPICalls.cs" rel="nofollow noreferrer">https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Hid.Net/Windows/HidAPICalls.cs</a></p>\n\n<pre><code>public static class HidAPICalls \n{\n    #region Constants\n    private const int DigcfDeviceinterface = 16;\n    private const int DigcfPresent = 2;\n    private const uint FileShareRead = 1;\n    private const uint FileShareWrite = 2;\n    private const uint GenericRead = 2147483648;\n    private const uint GenericWrite = 1073741824;\n    private const uint OpenExisting = 3;\n    private const int HIDP_STATUS_SUCCESS = 0x110000;\n    private const int HIDP_STATUS_INVALID_PREPARSED_DATA = -0x3FEF0000;\n    #endregion\n\n    #region API Calls\n\n    [DllImport("hid.dll", SetLastError = true)]\n    private static extern bool HidD_GetPreparsedData(SafeFileHandle hidDeviceObject, out IntPtr pointerToPreparsedData);\n\n    [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool HidD_GetManufacturerString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n    [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool HidD_GetProductString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n    [DllImport("hid.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool HidD_GetSerialNumberString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n    [DllImport("hid.dll", SetLastError = true)]\n    private static extern int HidP_GetCaps(IntPtr pointerToPreparsedData, out HidCollectionCapabilities hidCollectionCapabilities);\n\n    [DllImport("hid.dll", SetLastError = true)]\n    private static extern bool HidD_GetAttributes(SafeFileHandle hidDeviceObject, out HidAttributes attributes);\n\n    [DllImport("hid.dll", SetLastError = true)]\n    private static extern bool HidD_FreePreparsedData(ref IntPtr pointerToPreparsedData);\n\n    [DllImport("hid.dll", SetLastError = true)]\n    private static extern void HidD_GetHidGuid(ref Guid hidGuid);\n\n    private delegate bool GetString(SafeFileHandle hidDeviceObject, IntPtr pointerToBuffer, uint bufferLength);\n\n    #endregion\n\n    #region Helper Methods\n\n    #region Public Methods\n    public static HidAttributes GetHidAttributes(SafeFileHandle safeFileHandle)\n    {\n        var isSuccess = HidD_GetAttributes(safeFileHandle, out var hidAttributes);\n        WindowsDeviceBase.HandleError(isSuccess, "Could not get Hid Attributes");\n        return hidAttributes;\n    }\n\n    public static HidCollectionCapabilities GetHidCapabilities(SafeFileHandle readSafeFileHandle)\n    {\n        var isSuccess = HidD_GetPreparsedData(readSafeFileHandle, out var pointerToPreParsedData);\n        WindowsDeviceBase.HandleError(isSuccess, "Could not get pre parsed data");\n\n        var result = HidP_GetCaps(pointerToPreParsedData, out var hidCollectionCapabilities);\n        if (result != HIDP_STATUS_SUCCESS)\n        {\n            throw new Exception($"Could not get Hid capabilities. Return code: {result}");\n        }\n\n        isSuccess = HidD_FreePreparsedData(ref pointerToPreParsedData);\n        WindowsDeviceBase.HandleError(isSuccess, "Could not release handle for getting Hid capabilities");\n\n        return hidCollectionCapabilities;\n    }\n\n    public static string GetManufacturer(SafeFileHandle safeFileHandle)\n    {\n        return GetHidString(safeFileHandle, HidD_GetManufacturerString);\n    }\n\n    public static string GetProduct(SafeFileHandle safeFileHandle)\n    {\n        return GetHidString(safeFileHandle, HidD_GetProductString);\n    }\n\n    public static string GetSerialNumber(SafeFileHandle safeFileHandle)\n    {\n        return GetHidString(safeFileHandle, HidD_GetSerialNumberString);\n    }\n    #endregion\n\n    #region Private Static Methods\n    private static string GetHidString(SafeFileHandle safeFileHandle, GetString getString)\n    {\n        var pointerToBuffer = Marshal.AllocHGlobal(126);\n        var isSuccess = getString(safeFileHandle, pointerToBuffer, 126);\n        Marshal.FreeHGlobal(pointerToBuffer);\n        WindowsDeviceBase.HandleError(isSuccess, "Could not get Hid string");\n        return Marshal.PtrToStringUni(pointerToBuffer);     \n    }\n    #endregion\n\n    #endregion\n</code></pre>\n\n<p>}</p>\n\n<p><a href="https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Usb.Net/Windows/WinUsbApiCalls.cs" rel="nofollow noreferrer">https://github.com/MelbourneDeveloper/Device.Net/blob/master/src/Usb.Net/Windows/WinUsbApiCalls.cs</a></p>\n\n<pre><code>public static partial class WinUsbApiCalls\n{\n    #region Constants\n    public const int EnglishLanguageID = 1033;\n    public const uint DEVICE_SPEED = 1;\n    public const byte USB_ENDPOINT_DIRECTION_MASK = 0X80;\n    public const int WritePipeId = 0x80;\n\n    /// &lt;summary&gt;\n    /// Not sure where this constant is defined...\n    /// &lt;/summary&gt;\n    public const int DEFAULT_DESCRIPTOR_TYPE = 0x01;\n    public const int USB_STRING_DESCRIPTOR_TYPE = 0x03;\n    #endregion\n\n    #region API Calls\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_ControlTransfer(IntPtr InterfaceHandle, WINUSB_SETUP_PACKET SetupPacket, byte[] Buffer, uint BufferLength, ref uint LengthTransferred, IntPtr Overlapped);\n\n    [DllImport("winusb.dll", SetLastError = true, CharSet = CharSet.Auto)]\n    public static extern bool WinUsb_GetAssociatedInterface(SafeFileHandle InterfaceHandle, byte AssociatedInterfaceIndex, out SafeFileHandle AssociatedInterfaceHandle);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, ushort LanguageID, out USB_DEVICE_DESCRIPTOR deviceDesc, uint BufferLength, out uint LengthTransfered);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_GetDescriptor(SafeFileHandle InterfaceHandle, byte DescriptorType, byte Index, UInt16 LanguageID, byte[] Buffer, UInt32 BufferLength, out UInt32 LengthTransfered);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_Free(SafeFileHandle InterfaceHandle);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_Initialize(SafeFileHandle DeviceHandle, out SafeFileHandle InterfaceHandle);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_QueryDeviceInformation(IntPtr InterfaceHandle, uint InformationType, ref uint BufferLength, ref byte Buffer);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_QueryInterfaceSettings(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, out USB_INTERFACE_DESCRIPTOR UsbAltInterfaceDescriptor);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_QueryPipe(SafeFileHandle InterfaceHandle, byte AlternateInterfaceNumber, byte PipeIndex, out WINUSB_PIPE_INFORMATION PipeInformation);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_ReadPipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_SetPipePolicy(IntPtr InterfaceHandle, byte PipeID, uint PolicyType, uint ValueLength, ref uint Value);\n\n    [DllImport("winusb.dll", SetLastError = true)]\n    public static extern bool WinUsb_WritePipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);\n    #endregion\n\n    #region Public Methods\n    public static string GetDescriptor(SafeFileHandle defaultInterfaceHandle, byte index, string errorMessage)\n    {\n        var buffer = new byte[256];\n        var isSuccess = WinUsb_GetDescriptor(defaultInterfaceHandle, USB_STRING_DESCRIPTOR_TYPE, index, EnglishLanguageID, buffer, (uint)buffer.Length, out var transfered);\n        WindowsDeviceBase.HandleError(isSuccess, errorMessage);\n        var descriptor = new string(Encoding.Unicode.GetChars(buffer, 2, (int)transfered));\n        return descriptor.Substring(0, descriptor.Length - 1);\n    }\n    #endregion\n}\n</code></pre>\n\n<p>With any of these solutions you will either need to poll for the device on an interval, or use one of the API\'s native device listening classes. However, this library puts a layer across Hid, and USB on all platforms so that you can detect connections and disconnections easily: <a href="https://github.com/MelbourneDeveloper/Device.Net/wiki/Device-Listener" rel="nofollow noreferrer">https://github.com/MelbourneDeveloper/Device.Net/wiki/Device-Listener</a> . This is how you would use it:</p>\n\n<pre><code>internal class TrezorExample : IDisposable\n{\n    #region Fields\n    //Define the types of devices to search for. This particular device can be connected to via USB, or Hid\n    private readonly List&lt;FilterDeviceDefinition&gt; _DeviceDefinitions = new List&lt;FilterDeviceDefinition&gt;\n    {\n        new FilterDeviceDefinition{ DeviceType= DeviceType.Hid, VendorId= 0x534C, ProductId=0x0001, Label="Trezor One Firmware 1.6.x", UsagePage=65280 },\n        new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x534C, ProductId=0x0001, Label="Trezor One Firmware 1.6.x (Android Only)" },\n        new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C1, Label="Trezor One Firmware 1.7.x" },\n        new FilterDeviceDefinition{ DeviceType= DeviceType.Usb, VendorId= 0x1209, ProductId=0x53C0, Label="Model T" }\n    };\n    #endregion\n\n    #region Events\n    public event EventHandler TrezorInitialized;\n    public event EventHandler TrezorDisconnected;\n    #endregion\n\n    #region Public Properties\n    public IDevice TrezorDevice { get; private set; }\n    public DeviceListener DeviceListener { get; private set; }\n    #endregion\n\n    #region Event Handlers\n    private void DevicePoller_DeviceInitialized(object sender, DeviceEventArgs e)\n    {\n        TrezorDevice = e.Device;\n        TrezorInitialized?.Invoke(this, new EventArgs());\n    }\n\n    private void DevicePoller_DeviceDisconnected(object sender, DeviceEventArgs e)\n    {\n        TrezorDevice = null;\n        TrezorDisconnected?.Invoke(this, new EventArgs());\n    }\n    #endregion\n\n    #region Public Methods\n    public void StartListening()\n    {\n        TrezorDevice?.Dispose();\n        DeviceListener = new DeviceListener(_DeviceDefinitions, 3000);\n        DeviceListener.DeviceDisconnected += DevicePoller_DeviceDisconnected;\n        DeviceListener.DeviceInitialized += DevicePoller_DeviceInitialized;\n    }\n\n    public async Task InitializeTrezorAsync()\n    {\n        //Get the first available device and connect to it\n        var devices = await DeviceManager.Current.GetDevices(_DeviceDefinitions);\n        TrezorDevice = devices.FirstOrDefault();\n        await TrezorDevice.InitializeAsync();\n    }\n\n    public async Task&lt;byte[]&gt; WriteAndReadFromDeviceAsync()\n    {\n        //Create a buffer with 3 bytes (initialize)\n        var writeBuffer = new byte[64];\n        writeBuffer[0] = 0x3f;\n        writeBuffer[1] = 0x23;\n        writeBuffer[2] = 0x23;\n\n        //Write the data to the device\n        return await TrezorDevice.WriteAndReadAsync(writeBuffer);\n    }\n\n    public void Dispose()\n    {\n        TrezorDevice?.Dispose();\n    }\n    #endregion\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/68749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5903/']