///  <summary>
        ///  Uses a series of API calls to locate a HID-class device
        ///  by its Vendor ID and Product ID.
        ///  </summary>
        ///          
        ///  <returns>
        ///   True if the device is detected, False if not detected.
        ///  </returns>
        private Boolean FindTheHid(Int32 myVendorID, Int32 myProductID)
        {
            Boolean deviceFound = false;
            String[] devicePathName = new String[128];
            String functionName = "";
            Guid hidGuid = Guid.Empty;
            Int32 memberIndex = 0;
            Boolean success = false;

            try
            {
                myDeviceDetected = false;

                Tracer.Trace(string.Format("FindTheHid(0x{0:X04}, 0x{1:X04})", myVendorID, myProductID));

                //  ***
                //  API function: 'HidD_GetHidGuid

                //  Purpose: Retrieves the interface class GUID for the HID class.

                //  Accepts: 'A System.Guid object for storing the GUID.
                //  ***

                Hid.HidD_GetHidGuid(ref hidGuid);

                functionName = "GetHidGuid";
                Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                Tracer.Trace("  GUID for system HIDs: " + hidGuid.ToString());

                //  Fill an array with the device path names of all attached HIDs.

                deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                //  If there is at least one HID, attempt to read the Vendor ID and Product ID
                //  of each device until there is a match or all devices have been examined.

                if (deviceFound)
                {
                    memberIndex = 0;

                    do
                    {
                        //  ***
                        //  API function:
                        //  CreateFile

                        //  Purpose:
                        //  Retrieves a handle to a device.

                        //  Accepts:
                        //  A device path name returned by SetupDiGetDeviceInterfaceDetail
                        //  The type of access requested (read/write).
                        //  FILE_SHARE attributes to allow other processes to access the device while this handle is open.
                        //  A Security structure or IntPtr.Zero.
                        //  A creation disposition value. Use OPEN_EXISTING for devices.
                        //  Flags and attributes for files. Not used for devices.
                        //  Handle to a template file. Not used.

                        //  Returns: a handle without read or write access.
                        //  This enables obtaining information about all HIDs, even system
                        //  keyboards and mice.
                        //  Separate handles are used for reading and writing.
                        //  ***

                        hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                        functionName = "CreateFile";
                        Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                        Tracer.Trace("  Returned handle: " + hidHandle.ToString());

                        if (!hidHandle.IsInvalid)
                        {
                            //  The returned handle is valid,
                            //  so find out if this is the device we're looking for.

                            //  Set the Size property of DeviceAttributes to the number of bytes in the structure.

                            MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);

                            //  ***
                            //  API function:
                            //  HidD_GetAttributes

                            //  Purpose:
                            //  Retrieves a HIDD_ATTRIBUTES structure containing the Vendor ID,
                            //  Product ID, and Product Version Number for a device.

                            //  Accepts:
                            //  A handle returned by CreateFile.
                            //  A pointer to receive a HIDD_ATTRIBUTES structure.

                            //  Returns:
                            //  True on success, False on failure.
                            //  ***

                            success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                            if (success)
                            {
                                Tracer.Trace("  HIDD_ATTRIBUTES structure filled without error.");
                                Tracer.Trace("  Structure size: " + MyHid.DeviceAttributes.Size);
                                Tracer.Trace("  Vendor ID: " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
                                Tracer.Trace("  Product ID: " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));
                                Tracer.Trace("  Version Number: " + Convert.ToString(MyHid.DeviceAttributes.VersionNumber, 16));

                                //  Find out if the device matches the one we're looking for.

                                if ((MyHid.DeviceAttributes.VendorID == myVendorID) && (MyHid.DeviceAttributes.ProductID == myProductID))
                                {

                                    Tracer.Trace("  My device detected");

                                    //  Display the information in form's list box.

                                    Tracer.Trace("Device detected:");
                                    Tracer.Trace("  Vendor ID= " + Convert.ToString(MyHid.DeviceAttributes.VendorID, 16));
                                    Tracer.Trace("  Product ID = " + Convert.ToString(MyHid.DeviceAttributes.ProductID, 16));

                                    myDeviceDetected = true;

                                    //  Save the DevicePathName for OnDeviceChange().

                                    myDevicePathName = devicePathName[memberIndex];
                                }
                                else
                                {
                                    //  It's not a match, so close the handle.

                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                            else
                            {
                                //  There was a problem in retrieving the information.

                                Tracer.Trace("  Error in filling HIDD_ATTRIBUTES structure.");
                                myDeviceDetected = false;
                                hidHandle.Close();
                            }
                        }

                        //  Keep looking until we find the device or there are no devices left to examine.

                        memberIndex = memberIndex + 1;
                    }
                    while (!((myDeviceDetected || (memberIndex == devicePathName.Length))));
                }

                if (myDeviceDetected)
                {
                    //  The device was detected.
                    //  Register to receive notifications if the device is removed or attached.

                    success = MyDeviceManagement.RegisterForDeviceNotifications(myDevicePathName, m_mainForm.Handle, hidGuid, ref deviceNotificationHandle);

                    Tracer.Trace("RegisterForDeviceNotifications = " + success);

                    //  Learn the capabilities of the device.

                    MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);

                    if (success)
                    {
                        //  Find out if the device is a system mouse or keyboard.

                        hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);

                        //  Get the Input report buffer size.

                        GetInputReportBufferSize();

                        //  Get handles to use in requesting Input and Output reports.

                        readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);

                        functionName = "CreateFile, ReadHandle";
                        Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                        Tracer.Trace("  Returned handle: " + readHandle.ToString());

                        if (readHandle.IsInvalid)
                        {
                            exclusiveAccess = true;
                            Tracer.Error("The device is a system " + hidUsage + ". Applications can access Feature reports only.");
                        }
                        else
                        {
                            writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                            functionName = "CreateFile, WriteHandle";
                            Tracer.Trace(MyDebugging.ResultOfAPICall(functionName));
                            Tracer.Trace("  Returned handle: " + writeHandle.ToString());

                            //  Flush any waiting reports in the input buffer. (optional)

                            MyHid.FlushQueue(readHandle);
                        }
                    }
                }
                else
                {
                    //  The device wasn't detected.

                    Tracer.Error("Device not found.");
                }
                return myDeviceDetected;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex);
                throw;
            }
        }
 internal static void SafeCloseHandle(SafeFileHandle handle)
 {
   if (handle != null && !handle.IsInvalid)
     handle.Close();
 }
Example #3
0
            ///  <summary>
            ///  closes open handles to a device.
            ///  </summary>
            ///  
            ///  <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param>
            ///  <param name="readHandle"> the handle for reading Input reports from the device. </param>
            ///  <param name="writeHandle"> the handle for writing Output reports to the device. </param>
            internal void CancelTransfer(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle, IntPtr eventObject)
            {
                try
                {
                    //  ***
                    //  API function: CancelIo

                    //  Purpose: Cancels a call to ReadFile

                    //  Accepts: the device handle.

                    //  Returns: True on success, False on failure.
                    //  ***

                    FileIO.CancelIo(readHandle);

                    Debug.WriteLine( "************ReadFile error*************" );
                    String functionName = "CancelIo";
                    Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                    Debug.WriteLine( "" );

                    //  The failure may have been because the device was removed,
                    //  so close any open handles and
                    //  set myDeviceDetected=False to cause the application to
                    //  look for the device on the next attempt.

                    if ( ( !( hidHandle.IsInvalid ) ) )
                    {
                        hidHandle.Close();
                    }

                    if ( ( !( readHandle.IsInvalid ) ) )
                    {
                        readHandle.Close();
                    }

                    if ( ( !( writeHandle.IsInvalid ) ) )
                    {
                        writeHandle.Close();
                    }
                }
                catch ( Exception ex )
                {
                    DisplayException( MODULE_NAME, ex );
                    throw ;
                }
            }
Example #4
0
            ///  <summary>
            ///  writes an Output report to the device.
            ///  </summary>
            ///  
            ///  <param name="outputReportBuffer"> contains the report ID and report data. </param>
            ///  <param name="writeHandle"> handle to the device.  </param>
            ///  
            ///  <returns>
            ///   True on success. False on failure.
            ///  </returns>            
            internal override Boolean Write( Byte[] outputReportBuffer, SafeFileHandle writeHandle )
            {
                Int32 numberOfBytesWritten = 0;
                Boolean success = false;

                try
                {
                    //  The host will use an interrupt transfer if the the HID has an interrupt OUT
                    //  endpoint (requires USB 1.1 or later) AND the OS is NOT Windows 98 Gold (original version).
                    //  Otherwise the the host will use a control transfer.
                    //  The application doesn't have to know or care which type of transfer is used.

                    numberOfBytesWritten = 0;

                    //  ***
                    //  API function: WriteFile

                    //  Purpose: writes an Output report to the device.

                    //  Accepts:
                    //  A handle returned by CreateFile
                    //  An integer to hold the number of bytes written.

                    //  Returns: True on success, False on failure.
                    //  ***

                    success = FileIO.WriteFile(writeHandle, outputReportBuffer, outputReportBuffer.Length, ref numberOfBytesWritten, IntPtr.Zero);

                    Debug.Print( "WriteFile success = " + success );

                    if ( !( ( success ) ) )
                    {

                        if ( ( !( writeHandle.IsInvalid ) ) )
                        {
                            writeHandle.Close();
                        }
                    }
                    return success;
                }
                catch ( Exception ex )
                {
                    DisplayException( MODULE_NAME, ex );
                    throw ;
                }
            }
 private void CleanupHandle(SafeFileHandle handle)
 {
     if (handle != null && !handle.IsClosed)
     {
         InteropKernel32.CloseHandle(handle);
         handle.Close();
     }
 }
Example #6
0
 ///  <summary>
 ///  closes open handles to a device.
 ///  </summary>
 ///  
 ///  <param name="hidHandle"> the handle for learning about the device and exchanging Feature reports. </param>
 ///  <param name="readHandle"> the handle for reading Input reports from the device. </param>
 ///  <param name="writeHandle"> the handle for writing Output reports to the device. </param>
 private void CancelTransfer(SafeFileHandle hidHandle, SafeFileHandle readHandle, SafeFileHandle writeHandle) 
 {
     //  ***
     //  API function: CancelIo
         
     //  Purpose: Cancels a call to ReadFile
         
     //  Accepts: the device handle.
         
     //  Returns: True on success, False on failure.
     //  ***
         
     NativeMethods.CancelIo(readHandle);               
                                                
     //  The failure may have been because the device was removed,
     //  so close any open handles and
     //  set myDeviceDetected=False to cause the application to
     //  look for the device on the next attempt.
         
     if ( ( !( hidHandle.IsInvalid ) ) ) 
     { 
         hidHandle.Close(); 
     } 
         
     if ( ( !( readHandle.IsInvalid ) ) ) 
     { 
         readHandle.Close(); 
     } 
         
     if ( ( !( writeHandle.IsInvalid ) ) ) 
     { 
         writeHandle.Close(); 
     }
 }             
Example #7
0
        //-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //-------------------------------------------------------BEGIN CUT AND PASTE BLOCK-----------------------------------------------------------------------------------
        //This is a callback function that gets called when a Windows message is received by the form.
        //We will receive various different types of messages, but the ones we really want to use are the WM_DEVICECHANGE messages.
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                if (((int)m.WParam == DBT_DEVICEARRIVAL) || ((int)m.WParam == DBT_DEVICEREMOVEPENDING) || ((int)m.WParam == DBT_DEVICEREMOVECOMPLETE) || ((int)m.WParam == DBT_CONFIGCHANGED))
                {
                    //WM_DEVICECHANGE messages by themselves are quite generic, and can be caused by a number of different
                    //sources, not just your USB hardware device.  Therefore, must check to find out if any changes relavant
                    //to your device (with known VID/PID) took place before doing any kind of opening or closing of handles/endpoints.
                    //(the message could have been totally unrelated to your application/USB device)

                    if (CheckIfPresentAndGetUSBDevicePath())	//Check and make sure at least one device with matching VID/PID is attached
                    {
                        //If executes to here, this means the device is currently attached and was found.
                        //This code needs to decide however what to do, based on whether or not the device was previously known to be
                        //attached or not.
                        if ((AttachedState == false) || (AttachedButBroken == true))	//Check the previous attachment state
                        {
                            uint ErrorStatusWrite;
                            uint ErrorStatusRead;

                            //We obtained the proper device path (from CheckIfPresentAndGetUSBDevicePath() function call), and it
                            //is now possible to open read and write handles to the device.
                            WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                            ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
                            ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                            ErrorStatusRead = (uint)Marshal.GetLastWin32Error();

                            if ((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
                            {
                                AttachedState = true;		//Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
                                AttachedButBroken = false;
                                StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
                            }
                            else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
                            {
                                AttachedState = false;		//Let the rest of this application known not to read/write to the device.
                                AttachedButBroken = true;	//Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
                                if (ErrorStatusWrite == ERROR_SUCCESS)
                                    WriteHandleToUSBDevice.Close();
                                if (ErrorStatusRead == ERROR_SUCCESS)
                                    ReadHandleToUSBDevice.Close();
                            }
                        }
                        //else we did find the device, but AttachedState was already true.  In this case, don't do anything to the read/write handles,
                        //since the WM_DEVICECHANGE message presumably wasn't caused by our USB device.
                    }
                    else	//Device must not be connected (or not programmed with correct firmware)
                    {
                        if (AttachedState == true)		//If it is currently set to true, that means the device was just now disconnected
                        {
                            AttachedState = false;
                            WriteHandleToUSBDevice.Close();
                            ReadHandleToUSBDevice.Close();
                        }
                        AttachedState = false;
                        AttachedButBroken = false;
                    }
                }
            } //end of: if(m.Msg == WM_DEVICECHANGE)

            base.WndProc(ref m);
        }
Example #8
0
        //--------------- End of Global Varibles ------------------
        //-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //Need to check "Allow unsafe code" checkbox in build properties to use unsafe keyword.  Unsafe is needed to
        //properly interact with the unmanged C++ style APIs used to find and connect with the USB device.
        public unsafe Form1()
        {
            InitializeComponent();

            //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
            //-------------------------------------------------------BEGIN CUT AND PASTE BLOCK-----------------------------------------------------------------------------------
            //Additional constructor code

            //Initialize tool tips, to provide pop up help when the mouse cursor is moved over objects on the form.
            ANxVoltageToolTip.SetToolTip(this.ANxVoltage_lbl, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin.");
            ANxVoltageToolTip.SetToolTip(this.progressBar1, "If using a board/PIM without a potentiometer, apply an adjustable voltage to the I/O pin.");
            ToggleLEDToolTip.SetToolTip(this.ToggleLEDs_btn, "Sends a packet of data to the USB device.");
            PushbuttonStateTooltip.SetToolTip(this.PushbuttonState_lbl, "Try pressing pushbuttons on the USB demo board/PIM.");

            //Register for WM_DEVICECHANGE notifications.  This code uses these messages to detect plug and play connection/disconnection events for USB devices
            DEV_BROADCAST_DEVICEINTERFACE DeviceBroadcastHeader = new DEV_BROADCAST_DEVICEINTERFACE();
            DeviceBroadcastHeader.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
            DeviceBroadcastHeader.dbcc_size = (uint)Marshal.SizeOf(DeviceBroadcastHeader);
            DeviceBroadcastHeader.dbcc_reserved = 0;	//Reserved says not to use...
            DeviceBroadcastHeader.dbcc_classguid = InterfaceClassGuid;

            //Need to get the address of the DeviceBroadcastHeader to call RegisterDeviceNotification(), but
            //can't use "&DeviceBroadcastHeader".  Instead, using a roundabout means to get the address by
            //making a duplicate copy using Marshal.StructureToPtr().
            IntPtr pDeviceBroadcastHeader = IntPtr.Zero;  //Make a pointer.
            pDeviceBroadcastHeader = Marshal.AllocHGlobal(Marshal.SizeOf(DeviceBroadcastHeader)); //allocate memory for a new DEV_BROADCAST_DEVICEINTERFACE structure, and return the address
            Marshal.StructureToPtr(DeviceBroadcastHeader, pDeviceBroadcastHeader, false);  //Copies the DeviceBroadcastHeader structure into the memory already allocated at DeviceBroadcastHeaderWithPointer
            RegisterDeviceNotification(this.Handle, pDeviceBroadcastHeader, DEVICE_NOTIFY_WINDOW_HANDLE);

            //Now make an initial attempt to find the USB device, if it was already connected to the PC and enumerated prior to launching the application.
            //If it is connected and present, we should open read and write handles to the device so we can communicate with it later.
            //If it was not connected, we will have to wait until the user plugs the device in, and the WM_DEVICECHANGE callback function can process
            //the message and again search for the device.
            if(CheckIfPresentAndGetUSBDevicePath())	//Check and make sure at least one device with matching VID/PID is attached
            {
                uint ErrorStatusWrite;
                uint ErrorStatusRead;

                //We now have the proper device path, and we can finally open read and write handles to the device.
                WriteHandleToUSBDevice = CreateFile(DevicePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                ErrorStatusWrite = (uint)Marshal.GetLastWin32Error();
                ReadHandleToUSBDevice = CreateFile(DevicePath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                ErrorStatusRead = (uint)Marshal.GetLastWin32Error();

                if((ErrorStatusWrite == ERROR_SUCCESS) && (ErrorStatusRead == ERROR_SUCCESS))
                {
                    AttachedState = true;		//Let the rest of the PC application know the USB device is connected, and it is safe to read/write to it
                    AttachedButBroken = false;
                    StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
                }
                else //for some reason the device was physically plugged in, but one or both of the read/write handles didn't open successfully...
                {
                    AttachedState = false;		//Let the rest of this application known not to read/write to the device.
                    AttachedButBroken = true;	//Flag so that next time a WM_DEVICECHANGE message occurs, can retry to re-open read/write pipes
                    if(ErrorStatusWrite == ERROR_SUCCESS)
                        WriteHandleToUSBDevice.Close();
                    if(ErrorStatusRead == ERROR_SUCCESS)
                        ReadHandleToUSBDevice.Close();
                }
            }
            else	//Device must not be connected (or not programmed with correct firmware)
            {
                AttachedState = false;
                AttachedButBroken = false;
            }

            if (AttachedState == true)
            {
                StatusBox_txtbx.Text = "Device Found, AttachedState = TRUE";
            }
            else
            {
                StatusBox_txtbx.Text = "Device not found, verify connect/correct firmware";
            }

            ReadWriteThread.RunWorkerAsync();	//Recommend performing USB read/write operations in a separate thread.  Otherwise,
                                                //the Read/Write operations are effectively blocking functions and can lock up the
                                                //user interface if the I/O operations take a long time to complete.

            //-------------------------------------------------------END CUT AND PASTE BLOCK-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
        }
Example #9
0
            public String[] FindTheHids()
            {
                Boolean deviceFound = false;
                String[] devicePathName = new String[128];
                String functionName = "";
                Guid hidGuid = Guid.Empty;
                Int32 memberIndex = 0;
                Int16 myProductID = 0;
                Int16 myVendorID = 0;
                //Int32 product = 0;
                //Int32 vendor = 0;

                Boolean success = false;

                try
                {
                    myDeviceDetected = false;

                    //TODO: WTF is going on with this formatting?
                    //vendor = 0xAFEF;
                    //product = 0x0F01;
                    myVendorID = -20497;
                    myProductID = 3841;

                    //  ***
                    //  API function: 'HidD_GetHidGuid
                    //  Purpose: Retrieves the interface class GUID for the HID class.
                    //  Accepts: 'A System.Guid object for storing the GUID.
                    //  ***
                    Hid.HidD_GetHidGuid(ref hidGuid);

                    functionName = "GetHidGuid";
                    Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                    //Console.Out.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                    Debug.WriteLine("  GUID for system HIDs: " + hidGuid.ToString());
                    //Console.Out.WriteLine("  GUID for system HIDs: " + hidGuid.ToString());

                    //  Fill an array with the device path names of all attached HIDs.
                    deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                    for (int p = 0; p < devicePathName.Length; p++)
                    {
                        Console.Out.WriteLine(devicePathName[p]);
                    }

                    if (deviceFound)
                    {
                        for (int m = 0; m < devicePathName.Length; m++)
                        {
                            hidHandle = FileIO.CreateFile(devicePathName[memberIndex], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
                            functionName = "CreateFile";
                            Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));

                            if (!hidHandle.IsInvalid)
                            {
                                MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);
                                success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                                if (success)
                                {
                                    if ((MyHid.DeviceAttributes.VendorID == myVendorID) & (MyHid.DeviceAttributes.ProductID == myProductID))
                                    {
                                        Debug.WriteLine("  My device detected");
                                        //Console.Out.WriteLine("  My device detected");
                                        myDeviceDetected = true;
                                        //  Save the DevicePathName for OnDeviceChange().
                                        myDevicePathName = devicePathName[memberIndex];
                                    }
                                    else
                                    {
                                        //  It's not a match, so close the handle.
                                        myDeviceDetected = false;
                                        hidHandle.Close();
                                    }
                                }
                                else
                                {
                                    //  There was a problem in retrieving the information.
                                    Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                    //Console.Out.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                        }
                        if (myDeviceDetected)
                        {
                            MyHid.Capabilities = MyHid.GetDeviceCapabilities(hidHandle);
                            if (success)
                            {
                                //  Find out if the device is a system mouse or keyboard.
                                hidUsage = MyHid.GetHidUsage(MyHid.Capabilities);

                                //  Get the Input report buffer size.
                                //GetInputReportBufferSize();
                                //cmdInputReportBufferSize.Enabled = true;

                                //  Get handles to use in requesting Input and Output reports.
                                readHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_READ, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, FileIO.FILE_FLAG_OVERLAPPED, 0);

                                functionName = "CreateFile, ReadHandle";
                                Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                                //Console.Out.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                                Debug.WriteLine("  Returned handle: " + readHandle.ToString());
                                //Console.Out.WriteLine("  Returned handle: " + readHandle.ToString());
                                if (readHandle.IsInvalid)
                                {
                                    exclusiveAccess = true;
                                    //lstResults.Items.Add("The device is a system " + hidUsage + ".");
                                    //lstResults.Items.Add("Windows 2000 and Windows XP obtain exclusive access to Input and Output reports for this devices.");
                                    //lstResults.Items.Add("Applications can access Feature reports only.");
                                    //ScrollToBottomOfListBox();
                                }
                                else
                                {
                                    writeHandle = FileIO.CreateFile(myDevicePathName, FileIO.GENERIC_WRITE, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);

                                    functionName = "CreateFile, WriteHandle";
                                    Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                                    //Console.Out.WriteLine(MyDebugging.ResultOfAPICall(functionName));
                                    Debug.WriteLine("  Returned handle: " + writeHandle.ToString());
                                    //Console.Out.WriteLine("  Returned handle: " + writeHandle.ToString());

                                    //  Flush any waiting reports in the input buffer. (optional)

                                    MyHid.FlushQueue(readHandle);
                                }
                            }
                            else
                            {
                                //  The device wasn't detected.

                                //lstResults.Items.Add("Device not found.");
                                //cmdInputReportBufferSize.Enabled = false;
                                //cmdOnce.Enabled = true;

                                Debug.WriteLine(" Device not found.");
                                //Console.Out.WriteLine(" Device not found.");
                                //ScrollToBottomOfListBox();
                            }
                            //return myDeviceDetected;
                        }
                    }
                    return devicePathName;
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.ToString());
                    throw;
                }
            }
Example #10
0
            public String[] GetGuids()
            {
                Boolean deviceFound = false;
                String[] devicePathName = new String[128];
                Queue<string> queueDevicePathName = new Queue<string>();
                String functionName = "";
                String devpath;
                Guid hidGuid = Guid.Empty;
                Int32 memberIndex = 0;
                Int16 myVendorID = -20497;
                Int16 myProductID = 3841;
                Boolean success = false;

                Hid.HidD_GetHidGuid(ref hidGuid);
                deviceFound = MyDeviceManagement.FindDeviceFromGuid(hidGuid, ref devicePathName);

                    for (int p = 0; p < devicePathName.Length; p++)
                    {
                        Console.Out.WriteLine(devicePathName[p]);
                    }

                    if (deviceFound)
                    {
                        for (int m = 0; m < devicePathName.Length; m++)
                        {
                            hidHandle = FileIO.CreateFile(devicePathName[m], 0, FileIO.FILE_SHARE_READ | FileIO.FILE_SHARE_WRITE, IntPtr.Zero, FileIO.OPEN_EXISTING, 0, 0);
                            functionName = "CreateFile";
                            Debug.WriteLine(MyDebugging.ResultOfAPICall(functionName));

                            if (!hidHandle.IsInvalid)
                            {
                                MyHid.DeviceAttributes.Size = Marshal.SizeOf(MyHid.DeviceAttributes);
                                success = Hid.HidD_GetAttributes(hidHandle, ref MyHid.DeviceAttributes);

                                if (success)
                                {
                                    if ((MyHid.DeviceAttributes.VendorID == myVendorID) & (MyHid.DeviceAttributes.ProductID == myProductID))
                                    {
                                        Debug.WriteLine("  My device detected");
                                        //Console.Out.WriteLine("  My device detected");
                                        myDeviceDetected = true;
                                        //  Save the DevicePathName for OnDeviceChange().
                                        //myDevicePathName = devicePathName[memberIndex];
                                        devpath = devicePathName[m];
                                        hidHandle.Close();
                                        queueDevicePathName.Enqueue(devpath);
                                    }
                                    else
                                    {
                                        //  It's not a match, so close the handle.
                                        myDeviceDetected = false;
                                        hidHandle.Close();
                                    }
                                }
                                else
                                {
                                    //  There was a problem in retrieving the information.
                                    Debug.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                    //Console.Out.WriteLine("  Error in filling HIDD_ATTRIBUTES structure.");
                                    myDeviceDetected = false;
                                    hidHandle.Close();
                                }
                            }
                        }
                    }
                return queueDevicePathName.ToArray();
            }
Example #11
0
 private static void _CloseHandle(SafeFileHandle h)
 {
     try
       {
     if (h != null)
     {
       h.Close();
       h.Dispose();
     }
       }
       catch
       {
     //Eat...
       }
 }