Exemple #1
0
        public List<DeviceProperties> getUSBDevice(string VID, string PID)
        {
            List<DeviceProperties> objUSBDevice = new List<DeviceProperties>();

            Nullable<UInt32> MI = 0;

            if ("" != String.Empty)
            {
                MI = uint.Parse("", System.Globalization.NumberStyles.AllowHexSpecifier);
            }
            else
            {
                MI = null;
            }

            List<USBClass.DeviceProperties> ListOfUSBDeviceProperties = new List<USBClass.DeviceProperties>();
            if (USBClass.GetUSBDevice(uint.Parse(VID, System.Globalization.NumberStyles.AllowHexSpecifier), uint.Parse(PID, System.Globalization.NumberStyles.AllowHexSpecifier), ref ListOfUSBDeviceProperties, true, MI))
            {
                for (int i = 0; i < ListOfUSBDeviceProperties.Count; i++)
                {
                    DeviceProperties device = new DeviceProperties();

                    device.COMPort = ListOfUSBDeviceProperties[i].COMPort;
                    device.DeviceClass = ListOfUSBDeviceProperties[i].DeviceClass;
                    device.DeviceDescription = ListOfUSBDeviceProperties[i].DeviceDescription;
                    device.DeviceLocation = ListOfUSBDeviceProperties[i].DeviceLocation;
                    device.DeviceManufacturer = ListOfUSBDeviceProperties[i].DeviceManufacturer;
                    device.DevicePath = ListOfUSBDeviceProperties[i].DevicePath;
                    device.DevicePhysicalObjectName = ListOfUSBDeviceProperties[i].DevicePhysicalObjectName;
                    device.DeviceType = ListOfUSBDeviceProperties[i].DeviceType;
                    device.FriendlyName = ListOfUSBDeviceProperties[i].FriendlyName;
                    objUSBDevice.Add(device);
                }
            }

            return objUSBDevice;
        }
Exemple #2
0
        /*public static bool GetDeviceByClass(String DeviceInterfaceGUID)
        {
            IntPtr IntPtrBuffer = Marshal.AllocHGlobal(BUFFER_SIZE);
            Win32Wrapper.WinErrors LastError;
            bool Status = false;
            Guid DeviceGUID = new Guid(DeviceInterfaceGUID);

            try
            {
                //Get a handle to a device information set that contains all installed devices that support the Device Infomation Interface (GUID)
                IntPtr h = Win32Wrapper.SetupDiGetClassDevs(ref DeviceGUID, IntPtr.Zero, IntPtr.Zero, (uint)(Win32Wrapper.DIGCF.DIGCF_PRESENT | Win32Wrapper.DIGCF.DIGCF_DEVICEINTERFACE));
                if (h.ToInt32() != INVALID_HANDLE_VALUE)
                {
                    bool Success = true;
                    uint i = 0;
                    UInt32 RequiredSize = 0;

                    while (Success)
                    {
                        //Create a Device Interface Data structure
                        Win32Wrapper.SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new Win32Wrapper.SP_DEVICE_INTERFACE_DATA();
                        DeviceInterfaceData.cbSize = (uint)Marshal.SizeOf(DeviceInterfaceData);

                        //Start the enumeration
                        Success = Win32Wrapper.SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref DeviceGUID, i, ref DeviceInterfaceData);
                        if (!Success)
                        {
                            LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error();
                            if (LastError == Win32Wrapper.WinErrors.ERROR_NO_MORE_ITEMS)
                            {
                                Status = false;
                                break;
                            }
                            else
                            {
                                throw new Exception("Error enumerating devices!");
                            }
                        }

                        //Create a Device Info Data structure
                        Win32Wrapper.SP_DEVINFO_DATA DeviceInfoData = new Win32Wrapper.SP_DEVINFO_DATA();
                        DeviceInfoData.cbSize = (uint)Marshal.SizeOf(DeviceInfoData);

                        //Success = Win32Wrapper.SetupDiGetDeviceInterfaceDetail(h, ref DeviceInterfaceData, ref IntPtr.Zero, 0, out RequiredSize, ref IntPtr.Zero);
                        //Create a Device Interface Detail Data structure
                        Win32Wrapper.SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData = new Win32Wrapper.SP_DEVICE_INTERFACE_DETAIL_DATA();
                        if (IntPtr.Size == 8) //For 64 bit operating systems
                            DeviceInterfaceDetailData.cbSize = 8;
                        else
                            DeviceInterfaceDetailData.cbSize = (uint)(4 + Marshal.SystemDefaultCharSize); //For 32 bit systems

                        Success = Win32Wrapper.SetupDiGetDeviceInterfaceDetail(h, ref DeviceInterfaceData, ref DeviceInterfaceDetailData, BUFFER_SIZE, out RequiredSize, ref DeviceInfoData);

                        if (!Success)
                        {
                            throw new Exception("Error enumerating devices!");
                        }
                        
                        //Is this Port a USB Port? Ask the parent, then it's parent and so on
                        UInt32 StartingDevice = DeviceInfoData.DevInst;
                        Win32Wrapper.CRErrorCodes CRResult;
                        bool IsRemainDevices = true;

                        while(IsRemainDevices)
                        {
                            UInt32 hParentDevice = 0;

                            CRResult = (Win32Wrapper.CRErrorCodes)Win32Wrapper.CM_Get_Parent(out hParentDevice, StartingDevice, 0);

                            if (CRResult == Win32Wrapper.CRErrorCodes.CR_NO_SUCH_DEVNODE)
                            {
                                IsRemainDevices = true;//We hit the top of the PNP tree
                                break;
                            }
                            if (CRResult != Win32Wrapper.CRErrorCodes.CR_SUCCESS)
                            {
                                throw new Exception("Error calling CM_Get_Parent: " + CRResult.ToString());
                            }
                            if (IsRemainDevices)
                            {
                                CRResult = (Win32Wrapper.CRErrorCodes)Win32Wrapper.CM_Get_Device_ID(hParentDevice, IntPtrBuffer, BUFFER_SIZE, 0);
                                if (CRResult != Win32Wrapper.CRErrorCodes.CR_SUCCESS)
                                {
                                    throw new Exception("Error calling CM_Get_Device_ID: " + CRResult.ToString());
                                }

                                String DeviceID = Marshal.PtrToStringAuto(IntPtrBuffer);
                                if (DeviceID.StartsWith("USB\\"))
                                {
                                    Status = true;
                                }
                            }
                            //Do the next parent
                            StartingDevice = hParentDevice;
                        } //End of while(IsRemainDevices)
                        i++;
                    } //End of while (Success)
                } //End of if (h.ToInt32() != INVALID_HANDLE_VALUE)
                Win32Wrapper.SetupDiDestroyDeviceInfoList(h); //Clean up the old structure we no longer need.

                return Status;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Marshal.FreeHGlobal(IntPtrBuffer);
            }
        }*/

        /// <summary>
        /// Enumerate all USB devices and look for the device whose VID and PID are provided.
        /// </summary>
        /// <param name="VID">The Vendor ID of the USB Device.</param>
        /// <param name="PID">The Product ID of the USB Device.</param>
        /// <param name="ListOfDP">A list of Device Properties structures.</param>
        /// <param name="GetCOMPort">Set to True to retrieve the COM Port number if the Device is emulating a Serial Port.</param>
        /// <param name="MI">Optional: The Interface of the USB Device to be used when searching for Composite Devices.</param>
        /// <returns>True the Device is found.</returns>
        public static bool GetUSBDevice(UInt32 VID, UInt32 PID, ref List<DeviceProperties> ListOfDP, bool GetCOMPort, Nullable<UInt32> MI=null)
        {
            IntPtr IntPtrBuffer = Marshal.AllocHGlobal(BUFFER_SIZE);
            IntPtr h = IntPtr.Zero;
            Win32Wrapper.WinErrors LastError;
            DeviceProperties DP = new DeviceProperties();
            //bool Status = false;

            ListOfDP.Clear(); //Make sure the list of devices is empty
            try
            {
                string DevEnum = "USB";
                string ExpectedDeviceID = String.Empty;
                string ExpectedInterfaceID = String.Empty;

                ExpectedDeviceID = "VID_" + VID.ToString("X4") + "&" + "PID_" + PID.ToString("X4");
                ExpectedDeviceID = ExpectedDeviceID.ToLowerInvariant();

                if(MI != null)
                {
                    ExpectedInterfaceID = "MI_" + ((UInt32)MI).ToString("X2");
                    ExpectedInterfaceID = ExpectedInterfaceID.ToLowerInvariant();
                }                
                
                h = Win32Wrapper.SetupDiGetClassDevs(IntPtr.Zero, DevEnum, IntPtr.Zero, (int)(Win32Wrapper.DIGCF.DIGCF_PRESENT | Win32Wrapper.DIGCF.DIGCF_ALLCLASSES));
                if (h.ToInt32() != INVALID_HANDLE_VALUE)
                {
                    bool Success = true;
                    uint i = 0;
                    while (Success)
                    {
                        if (Success)
                        {
                            UInt32 RequiredSize = 0;
                            UInt32 RegType = 0;
                            IntPtr Ptr = IntPtr.Zero;

                            //Create a Device Info Data structure
                            Win32Wrapper.SP_DEVINFO_DATA DevInfoData = new Win32Wrapper.SP_DEVINFO_DATA();
                            DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);
                            Success = Win32Wrapper.SetupDiEnumDeviceInfo(h, i, ref DevInfoData);

                            if (Success)
                            {
                                //Get the required buffer size
                                //First query for the size of the Hardware ID, so we know the size of the needed buffer to allocate to store the data.
                                Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtr.Zero, 0, ref RequiredSize);

                                LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error();
                                if (LastError == Win32Wrapper.WinErrors.ERROR_INSUFFICIENT_BUFFER)
                                {
                                    /*if (RequiredSize > BUFFER_SIZE)
                                    {
                                        Status = false;
                                    }
                                    else*/
                                    if (RequiredSize <= BUFFER_SIZE)
                                    {
                                        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_HARDWAREID, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                        {
                                            string HardwareID = Marshal.PtrToStringAuto(IntPtrBuffer);
                                            HardwareID = HardwareID.ToLowerInvariant();
                                            if (
                                                HardwareID.Contains(ExpectedDeviceID) &&
                                                    (
                                                        ((MI != null) && HardwareID.Contains(ExpectedInterfaceID))
                                                        ||
                                                        ((MI == null) && (!HardwareID.Contains("mi")))
                                                    )
                                                )
                                            {
                                                //Status = true; //Found device

                                                DP.FriendlyName = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_FRIENDLYNAME, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.FriendlyName = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DeviceType = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_DEVTYPE, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DeviceType = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DeviceClass = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_CLASS, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DeviceClass = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DeviceManufacturer = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_MFG, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DeviceManufacturer = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DeviceLocation = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_LOCATION_INFORMATION, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DeviceLocation = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DevicePath = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_LOCATION_PATHS, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DevicePath = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DevicePhysicalObjectName = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DevicePhysicalObjectName = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.DeviceDescription = String.Empty;
                                                if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, (UInt32)Win32Wrapper.SPDRP.SPDRP_DEVICEDESC, ref RegType, IntPtrBuffer, BUFFER_SIZE, ref RequiredSize))
                                                {
                                                    DP.DeviceDescription = Marshal.PtrToStringAuto(IntPtrBuffer);
                                                }

                                                DP.COMPort = String.Empty;
                                                if (GetCOMPort)
                                                {
                                                    //Open the Device Parameters Key of the device
                                                    IntPtr hDeviceRegistryKey;

                                                    hDeviceRegistryKey = Win32Wrapper.SetupDiOpenDevRegKey(h, ref DevInfoData, (UInt32)Win32Wrapper.DICS_FLAG.DICS_FLAG_GLOBAL, 0, (UInt32)Win32Wrapper.DIREG.DIREG_DEV, (UInt32)Win32Wrapper.REGKEYSECURITY.KEY_READ);
                                                    if (hDeviceRegistryKey.ToInt32() == INVALID_HANDLE_VALUE)
                                                    {
                                                        LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error();
                                                        break; //throw new Exception("Error opening the Registry: " + LastError.ToString());
                                                    }
                                                    else
                                                    {
                                                        UInt32 Type = 0;
                                                        System.Text.StringBuilder Data = new System.Text.StringBuilder(BUFFER_SIZE);
                                                        UInt32 Size = (UInt32)Data.Capacity;
                                                        int Result;

                                                        Result = Win32Wrapper.RegQueryValueEx(hDeviceRegistryKey, "PortName", 0, out Type, Data, ref Size);
                                                        if (Result == (int)Win32Wrapper.WinErrors.ERROR_SUCCESS)
                                                        {
                                                            DP.COMPort = Data.ToString();
                                                        }

                                                        //Close Registry
                                                        Win32Wrapper.RegCloseKey(hDeviceRegistryKey);
                                                    }
                                                }

                                                ListOfDP.Add(DP); //Add details of the found device in the list
                                                //break;
                                            } //End of if (HardwareID.Contains(ExpectedDeviceID) && ...)
                                            //else
                                            //{
                                            //    Status = false;
                                            //} 
                                        }
                                    } //End of if (RequiredSize <= BUFFER_SIZE) //if (RequiredSize > BUFFER_SIZE)
                                } //End of if (LastError == Win32Wrapper.WinErrors.ERROR_INSUFFICIENT_BUFFER)
                            } // End of if (Success)
                        } // End of if (Success)
                        else
                        {
                            LastError = (Win32Wrapper.WinErrors)Marshal.GetLastWin32Error();
                            //Status = false;
                        }
                        i++;
                    } // End of while (Success)
                } //End of if (h.ToInt32() != INVALID_HANDLE_VALUE)

                return (ListOfDP.Count > 0);
                //return Status;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                Win32Wrapper.SetupDiDestroyDeviceInfoList(h); //Clean up the old structure we no longer need.
                Marshal.FreeHGlobal(IntPtrBuffer);
            }
        }