Académique Documents
Professionnel Documents
Culture Documents
SafeHandles;
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace UsbLibrary
{
#region Custom exception
/// <summary>
/// Generic HID device exception
/// </summary>
public class HIDDeviceException : ApplicationException
{
public HIDDeviceException(string strMessage) : base(strMessage) { }
CloseHandle(m_hHandle);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
#endregion
#region Privates/protected
/// <summary>
/// Initialises the device
/// </summary>
/// <param name="strPath">Path to the device</param>
private void Initialise(string strPath)
{
// Create the file from the device path
m_hHandle = CreateFile(strPath, GENERIC_READ | GENERIC_WRITE, 0,
IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
int index = 0;
HIDDevice oNewDevice = null;
while (SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, IntPtr.Zero, ref
hidGuid, index, ref deviceInfoData))
{
string strDevicePath = GetDevicePath(hardwareDeviceInfo, ref
deviceInfoData); // get the device path (see helper method 'GetDevicePath')
if (!string.IsNullOrEmpty(strDevicePath))
{
if (strDevicePath.IndexOf(strSearch) >= 0) // do a string
search, if we find the VID/PID string then we found our device!
{
oNewDevice =
(HIDDevice)Activator.CreateInstance(oType); // create an instance of the class for
this device
oNewDevice.Initialise(strDevicePath); // initialise it
with the device path
break;
}
}
index++;
}
return oNewDevice; // oops, didn't find our device
}
#endregion
#region Publics
/// <summary>
/// Event handler called when device has been removed
/// </summary>
public event EventHandler OnDeviceRemoved;
/// <summary>
/// Accessor for output report length
/// </summary>
public int OutputReportLength
{
get
{
return m_nOutputReportLength;
}
}
/// <summary>
/// Accessor for input report length
/// </summary>
public int InputReportLength
{
get
{
return m_nInputReportLength;
}
}
/// <summary>
/// Virtual method to create an input report for this device. Override to
use.
/// </summary>
/// <returns>A shiny new input report</returns>
public virtual InputReport CreateInputReport()
{
return null;
}
#endregion
}
}