Beispiel #1
0
 /// <summary>
 /// Set device state.
 /// </summary>
 /// <param name="match"></param>
 /// <param name="enable"></param>
 /// <returns>Success state.</returns>
 /// <remarks>
 /// This is nearly identical to the method above except it
 /// tries to match the hardware description against the criteria
 /// passed in.  If a match is found, that device will the be
 /// enabled or disabled based on bEnable.
 /// Errors:   This method may throw the following exceptions.
 ///           Failed to enumerate device tree!
 /// </remarks>
 public static bool SetDeviceState(string deviceId, bool enable)
 {
     try
     {
         Guid   myGUID        = System.Guid.Empty;
         IntPtr deviceInfoSet = SetupDiGetClassDevs(myGUID, null, IntPtr.Zero, DIGCF.DIGCF_ALLCLASSES | DIGCF.DIGCF_PRESENT);
         if (deviceInfoSet.ToInt32() == INVALID_HANDLE_VALUE)
         {
             return(false);
         }
         var deviceInfoData = new SP_DEVICE_INTERFACE_DATA();
         deviceInfoData.Initialize();
         deviceInfoData.Flags = 0;
         deviceInfoData.InterfaceClassGuid = System.Guid.Empty;
         deviceInfoData.Reserved           = IntPtr.Zero;
         for (var i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, ref deviceInfoData); i++)
         {
             var currentDeviceId = GetDeviceId(deviceInfoData.Flags);
             if (deviceId == currentDeviceId)
             {
                 SetDeviceState(deviceInfoSet, deviceInfoData, enable);
             }
         }
         SetupDiDestroyDeviceInfoList(deviceInfoSet);
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to enumerate device tree!", ex);
         //return false;
     }
     return(true);
 }
Beispiel #2
0
        public static SP_DEVICE_INTERFACE_DATA?GetDeviceInfo(IntPtr deviceInfoSet, string deviceInstanceId)
        {
            var da = new SP_DEVICE_INTERFACE_DATA();

            da.Initialize();
            var result = SetupDiOpenDeviceInfo(deviceInfoSet, deviceInstanceId, IntPtr.Zero, 0, ref da);

            if (!result)
            {
                return(null);
            }
            return(da);
        }
Beispiel #3
0
 public static DeviceInfo[] GetDevices(Guid classGuid, DIGCF flags, string deviceId, int vid, int pid, int rev)
 {
     lock (GetDevicesLock)
     {
         IntPtr deviceInfoSet = SetupDiGetClassDevs(classGuid, null, IntPtr.Zero, flags);                 //  | DIGCF.DIGCF_PRESENT
         if (deviceInfoSet.ToInt32() == ERROR_INVALID_HANDLE_VALUE)
         {
             throw new Exception("Invalid Handle");
         }
         var list           = new List <DeviceInfo>();
         var deviceInfoData = new SP_DEVICE_INTERFACE_DATA();
         deviceInfoData.Initialize();
         int i;
         for (i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, ref deviceInfoData); i++)
         {
             var currentDeviceId = GetDeviceId(deviceInfoData.Flags);
             if (!string.IsNullOrEmpty(deviceId) && deviceId != currentDeviceId)
             {
                 continue;
             }
             var device = GetDeviceInfo(deviceInfoSet, deviceInfoData, deviceId);
             if (vid > 0 && device.VendorId != vid)
             {
                 continue;
             }
             if (pid > 0 && device.ProductId != pid)
             {
                 continue;
             }
             if (rev > 0 && device.Revision != rev)
             {
                 continue;
             }
             list.Add(device);
         }
         SetupDiDestroyDeviceInfoList(deviceInfoSet);
         return(list.OrderBy(x => x.ClassDescription).ThenBy(x => x.Description).ToArray());
     }
 }
Beispiel #4
0
        /// <summary>
        /// Enumerate Interfaces.
        /// </summary>
        static void _EnumDeviceInterfaces(Func <IntPtr, SP_DEVICE_INTERFACE_DATA, bool> callback)
        {
            var hidGuid = Guid.Empty;

            NativeMethods.HidD_GetHidGuid(ref hidGuid);
            lock (GetDevicesLock)
            {
                var infoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE);
                if (infoSet.ToInt64() == ERROR_INVALID_HANDLE_VALUE)
                {
                    throw new Exception("Invalid Handle");
                }
                var interfaceData = new SP_DEVICE_INTERFACE_DATA();
                interfaceData.Initialize();
                for (var i = 0; NativeMethods.SetupDiEnumDeviceInterfaces(infoSet, IntPtr.Zero, ref hidGuid, i, ref interfaceData); i++)
                {
                    if (!callback.Invoke(infoSet, interfaceData))
                    {
                        break;
                    }
                }
                NativeMethods.SetupDiDestroyDeviceInfoList(infoSet);
            }
        }
Beispiel #5
0
 public static DeviceInfo GetParentDevice(Guid classGuid, DIGCF flags, string deviceId)
 {
     lock (GetDevicesLock)
     {
         IntPtr deviceInfoSet = SetupDiGetClassDevs(classGuid, null, IntPtr.Zero, flags);                 //  | DIGCF.DIGCF_PRESENT
         if (deviceInfoSet.ToInt32() == ERROR_INVALID_HANDLE_VALUE)
         {
             throw new Exception("Invalid Handle");
         }
         DeviceInfo device         = null;
         var        deviceInfoData = new SP_DEVICE_INTERFACE_DATA();
         deviceInfoData.Initialize();
         int i;
         for (i = 0; SetupDiEnumDeviceInfo(deviceInfoSet, i, ref deviceInfoData); i++)
         {
             if (deviceId == GetDeviceId(deviceInfoData.Flags))
             {
                 uint parentDeviceInstance = 0;
                 var  CRResult             = CM_Get_Parent(out parentDeviceInstance, deviceInfoData.Flags, 0);
                 if (CRResult == CR.CR_NO_SUCH_DEVNODE)
                 {
                     break;
                 }
                 if (CRResult != CR.CR_SUCCESS)
                 {
                     break;
                 }
                 var parentDeviceId = GetDeviceId(parentDeviceInstance);
                 device = GetDevice(classGuid, flags, parentDeviceId);
                 break;
             }
         }
         SetupDiDestroyDeviceInfoList(deviceInfoSet);
         return(device);
     }
 }
        //--------------------------------------------------------------------------
        // Discovery
        //--------------------------------------------------------------------------

        public static List<KnownNXT> FindDeviceFromGuid(Guid guidDeviceInstance)
        // Find all connected instances of this kind of USB device
            {
            IntPtr hDeviceInfoSet = INVALID_HANDLE_VALUE;
            try
                {
                hDeviceInfoSet = SetupDiGetClassDevs(ref guidDeviceInstance, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
                if (INVALID_HANDLE_VALUE==hDeviceInfoSet)
                    ThrowWin32Error();

                SP_DEVICE_INTERFACE_DATA did = new SP_DEVICE_INTERFACE_DATA();
                did.Initialize();

                List<KnownNXT> result = new List<KnownNXT>();

                for (int iMember=0 ;; iMember++)
                    {
                    // Get did of the next interface
                    bool fSuccess = SetupDiEnumDeviceInterfaces
                        (hDeviceInfoSet,
                        IntPtr.Zero,
                        ref guidDeviceInstance,
                        iMember,
                        out did);

                    if (!fSuccess)
                        {
                        break;  // Done! no more 
                        }
                    else
                        {
                        // A device is present. Get details
                        SP_DEVICE_INTERFACE_DETAIL_DATA detail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                        detail.Initialize();

                        int cbRequired;
                        ThrowIfFail(SetupDiGetDeviceInterfaceDetail
                            (hDeviceInfoSet,
                            ref did,
                            ref detail,
                            Marshal.SizeOf(detail),
                            out cbRequired,
                            IntPtr.Zero));

                        result.Add(new KnownNXT(KnownNXT.CONNECTIONTYPE.USB, detail.DevicePath));
                        }
                    }

                return result;
                }
            finally
                {
                if (hDeviceInfoSet != IntPtr.Zero && hDeviceInfoSet != INVALID_HANDLE_VALUE)
                    {
                    SetupDiDestroyDeviceInfoList(hDeviceInfoSet);
                    }
                }
            }
Beispiel #7
0
        public static DeviceInfo[] GetInterfaces()
        {
            var  list    = new List <DeviceInfo>();
            Guid hidGuid = Guid.Empty;

            NativeMethods.HidD_GetHidGuid(ref hidGuid);
            int requiredSize3 = 0;
            var interfaceData = new SP_DEVICE_INTERFACE_DATA();

            interfaceData.Initialize();
            List <string> serials       = new List <string>();
            var           deviceInfoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE);

            for (int i2 = 0; NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref hidGuid, i2, ref interfaceData); i2++)
            {
                var deviceInfoData = new SP_DEVINFO_DATA();
                deviceInfoData.Initialize();
                bool   success    = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref requiredSize3, IntPtr.Zero);
                IntPtr ptrDetails = Marshal.AllocHGlobal(requiredSize3);
                Marshal.WriteInt32(ptrDetails, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);
                success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, ptrDetails, requiredSize3, ref requiredSize3, ref deviceInfoData);
                var interfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(ptrDetails, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                var di = GetDeviceInfo(deviceInfoSet, deviceInfoData);
                di.DevicePath = interfaceDetail.DevicePath;
                var deviceHandle = deviceInfoData.DevInst;
                Marshal.FreeHGlobal(ptrDetails);
                // Open the device as a file so that we can query it with HID and read/write to it.
                var devHandle = NativeMethods.CreateFile(
                    interfaceDetail.DevicePath,
                    0,
                    FileShare.ReadWrite,
                    IntPtr.Zero,
                    FileMode.Open,
                    0, //WinNT.Overlapped
                    IntPtr.Zero
                    );
                if (devHandle.IsInvalid)
                {
                    continue;
                }
                var ha = new HIDD_ATTRIBUTES();
                ha.Size = Marshal.SizeOf(ha);
                var    success2 = NativeMethods.HidD_GetAttributes(devHandle, ref ha);
                string serial   = "";
                string phdesc   = "";
                if (success2)
                {
                    IntPtr    preparsedDataPtr = new IntPtr();
                    HIDP_CAPS caps             = new HIDP_CAPS();
                    // Read out the 'pre-parsed data'.
                    NativeMethods.HidD_GetPreparsedData(devHandle, ref preparsedDataPtr);
                    // feed that to GetCaps.
                    NativeMethods.HidP_GetCaps(preparsedDataPtr, ref caps);
                    // Free the 'pre-parsed data'.
                    NativeMethods.HidD_FreePreparsedData(ref preparsedDataPtr);
                    // This could fail if the device was recently attached.
                    // Maximum string length is 126 wide characters (2 bytes each) (not including the terminating NULL character).
                    ulong capacity = (uint)(126 * Marshal.SystemDefaultCharSize + 2);
                    var   sb       = new StringBuilder((int)capacity, (int)capacity);
                    // Override manufacturer if found.
                    if (NativeMethods.HidD_GetManufacturerString(devHandle, sb, sb.Capacity) && sb.Length > 0)
                    {
                        di.Manufacturer = sb.ToString();
                    }
                    // Override ProductName if Found.
                    if (NativeMethods.HidD_GetProductString(devHandle, sb, sb.Capacity) && sb.Length > 0)
                    {
                        di.Description = sb.ToString();
                    }
                    serial = NativeMethods.HidD_GetSerialNumberString(devHandle, sb, sb.Capacity)
                        ? sb.ToString() : "";
                    phdesc = NativeMethods.HidD_GetPhysicalDescriptor(devHandle, sb, sb.Capacity)
                        ? sb.ToString() : "";
                }
                uint   parentDeviceInstance = 0;
                string parentDeviceId       = null;
                var    CRResult             = NativeMethods.CM_Get_Parent(out parentDeviceInstance, deviceHandle, 0);
                if (CRResult == CR.CR_SUCCESS)
                {
                    parentDeviceId = GetDeviceId(parentDeviceInstance);
                }
                list.Add(di);
                serials.Add(phdesc);
                devHandle.Close();
            }
            NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet);
            deviceInfoSet = IntPtr.Zero;
            return(list.ToArray());
        }
Beispiel #8
0
        public static DeviceInfo[] GetInterfaces(string[] devicePaths = null)
        {
            var  list    = new List <DeviceInfo>();
            Guid hidGuid = Guid.Empty;

            NativeMethods.HidD_GetHidGuid(ref hidGuid);
            int           requiredSize3    = 0;
            List <string> devicePathNames3 = new List <string>();
            var           interfaceData    = new SP_DEVICE_INTERFACE_DATA();
            List <string> serials          = new List <string>();

            interfaceData.Initialize();
            var deviceInfoSet = NativeMethods.SetupDiGetClassDevs(hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF.DIGCF_DEVICEINTERFACE);

            for (int i2 = 0; NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref hidGuid, i2, ref interfaceData); i2++)
            {
                var deviceInfoData = new SP_DEVINFO_DATA();
                deviceInfoData.Initialize();
                bool   success    = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, IntPtr.Zero, 0, ref requiredSize3, IntPtr.Zero);
                IntPtr ptrDetails = Marshal.AllocHGlobal(requiredSize3);
                Marshal.WriteInt32(ptrDetails, (IntPtr.Size == 4) ? (4 + Marshal.SystemDefaultCharSize) : 8);
                success = NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref interfaceData, ptrDetails, requiredSize3, ref requiredSize3, ref deviceInfoData);
                var interfaceDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA)Marshal.PtrToStructure(ptrDetails, typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                var devicePath      = interfaceDetail.DevicePath;
                if (devicePaths != null && !devicePaths.Contains(devicePath))
                {
                    continue;
                }
                var deviceHandle = deviceInfoData.DevInst;
                var deviceId     = GetDeviceId(deviceHandle);
                devicePathNames3.Add(devicePath);
                Marshal.FreeHGlobal(ptrDetails);
                var accessRights = WinNT.GENERIC_READ | WinNT.GENERIC_WRITE;
                var shareModes   = WinNT.FILE_SHARE_READ | WinNT.FILE_SHARE_WRITE;
                // Open the device as a file so that we can query it with HID and read/write to it.
                var devHandle = NativeMethods.CreateFile(
                    interfaceDetail.DevicePath,
                    accessRights,
                    shareModes,
                    IntPtr.Zero,
                    WinNT.OPEN_EXISTING,
                    WinNT.Overlapped,
                    IntPtr.Zero
                    );
                if (devHandle.IsInvalid)
                {
                    continue;
                }
                var ha = new HIDD_ATTRIBUTES();
                ha.Size = Marshal.SizeOf(ha);
                var    success2 = NativeMethods.HidD_GetAttributes(devHandle, ref ha);
                string serial   = "";
                string vendor   = "";
                string product  = "";
                string phdesc   = "";
                if (success2)
                {
                    IntPtr    preparsedDataPtr = new IntPtr();
                    HIDP_CAPS caps             = new HIDP_CAPS();
                    // Read out the 'preparsed data'.
                    NativeMethods.HidD_GetPreparsedData(devHandle, ref preparsedDataPtr);
                    // feed that to GetCaps.
                    NativeMethods.HidP_GetCaps(preparsedDataPtr, ref caps);
                    // Free the 'preparsed data'.
                    NativeMethods.HidD_FreePreparsedData(ref preparsedDataPtr);
                    // This could fail if the device was recently attached.
                    uint   capacity = 126;
                    IntPtr buffer   = Marshal.AllocHGlobal((int)capacity);
                    serial = NativeMethods.HidD_GetSerialNumberString(devHandle, buffer, capacity)
                                                ? Marshal.PtrToStringAuto(buffer) : "";
                    vendor = NativeMethods.HidD_GetManufacturerString(devHandle, buffer, capacity)
                                                ? Marshal.PtrToStringAuto(buffer) : "";
                    product = NativeMethods.HidD_GetProductString(devHandle, buffer, capacity)
                                                ? Marshal.PtrToStringAuto(buffer) : "";
                    phdesc = NativeMethods.HidD_GetPhysicalDescriptor(devHandle, buffer, capacity)
                                                ? Marshal.PtrToStringAuto(buffer) : "";
                    // Free resources.
                    Marshal.FreeHGlobal(buffer);
                }
                uint   parentDeviceInstance = 0;
                string parentDeviceId       = null;
                var    CRResult             = NativeMethods.CM_Get_Parent(out parentDeviceInstance, deviceHandle, 0);
                if (CRResult == CR.CR_SUCCESS)
                {
                    parentDeviceId = GetDeviceId(parentDeviceInstance);
                }

                var di = new DeviceInfo(deviceId, deviceHandle, parentDeviceId, devicePath, vendor, product, hidGuid, "", DeviceNodeStatus.DN_MANUAL, ha.VendorID, ha.ProductID, ha.VersionNumber);
                list.Add(di);
                serials.Add(phdesc);
                devHandle.Close();
            }
            NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet);
            deviceInfoSet = IntPtr.Zero;
            return(list.ToArray());
        }