Beispiel #1
0
        public void OpenDevice(String DevicePath)
        {
            uint ErrorStatusWrite;
            uint ErrorStatusRead;

            // Close device first
            CloseDevice();
            // Open WriteHandle
            WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            ErrorStatusWrite       = (uint)Marshal.GetLastWin32Error();
            // Open ReadHandle
            ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            ErrorStatusRead       = (uint)Marshal.GetLastWin32Error();
            // Check if both handles were opened successfully
            if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
            {
                ConnectionStatus = UsbConnectionStatus.Connected;
            }
            else // For some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully
            {
                ConnectionStatus = UsbConnectionStatus.NotWorking;
                if (ErrorStatusWrite == ERROR_SUCCESS)
                {
                    WriteHandleToUSBDevice.Close();
                }

                if (ErrorStatusRead == ERROR_SUCCESS)
                {
                    ReadHandleToUSBDevice.Close();
                }
            }
            // Raise event if there are any subscribers
            if (RaiseConnectionStatusChangedEvent != null)
            {
                RaiseConnectionStatusChangedEvent(this, new ConnectionStatusEventArgs(ConnectionStatus));
            }
            // Start async thread if connection has been established
            if (ConnectionStatus == UsbConnectionStatus.Connected)
            {
                //UsbThread.RunWorkerAsync();
            }
        }
Beispiel #2
0
 // Close connection to the USB device
 public void CloseDevice()
 {
     // Save current status
     UsbConnectionStatus previousStatus = ConnectionStatus;
     // Close write and read handles if a device is connected
     if (ConnectionStatus==UsbConnectionStatus.Connected)      
     {
         WriteHandleToUSBDevice.Close();
         ReadHandleToUSBDevice.Close();
     }
     // Set status to disconnected
     ConnectionStatus = UsbConnectionStatus.Disconnected;
     // Stop async thread if connection has been established
     //UsbThread.CancelAsync();
     // Raise event if the status has changed and if there are any subscribers
     if (ConnectionStatus!=previousStatus)
     {
         if (RaiseConnectionStatusChangedEvent != null)
         {
             RaiseConnectionStatusChangedEvent(this, new ConnectionStatusEventArgs(ConnectionStatus));
         }
     }
 }
Beispiel #3
0
 public ConnectionStatusEventArgs(UsbConnectionStatus status)
 {
     this.ConnectionStatus = status;
 }