static extern Boolean SetupDiGetDeviceInterfaceDetail(
    IntPtr hDevInfo,
    ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
    ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
    UInt32 deviceInterfaceDetailDataSize,
    IntPtr requiredSize,                     // Allow null
    IntPtr deviceInfoData                    // Allow null
 );
Example #2
0
 static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
     UInt32 deviceInterfaceDetailDataSize,
     IntPtr requiredSize,                    // Allow null
     IntPtr deviceInfoData                   // Allow null
     );
 static extern Boolean SetupDiGetDeviceInterfaceDetail(
    IntPtr hDevInfo,
    ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
    ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
    UInt32 deviceInterfaceDetailDataSize,
    out UInt32 requiredSize,
    ref SP_DEVINFO_DATA deviceInfoData
 );
Example #4
0
 public static extern Boolean SetupDiGetDeviceInterfaceDetailW(
     IntPtr DeviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,
     Int32 DeviceInterfaceDetailDataSize,
     ref UInt32 RequiredSize,
     ref SP_DEVINFO_DATA DeviceInfoData
     );
Example #5
0
 protected static extern bool SetupDiGetDeviceInterfaceDetail
     (SafeDevInfoTableHandle lpDeviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA oInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA oDetailData,
     uint nDeviceInterfaceDetailDataSize,
     IntPtr nRequiredSize,
     IntPtr lpDeviceInfoData
     );
Example #6
0
 public static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
     UInt32 deviceInterfaceDetailDataSize,
     out UInt32 requiredSize,
     ref SP_DEVINFO_DATA deviceInfoData
     );
Example #7
0
 private static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
     Int32 deviceInterfaceDetailDataSize,
     IntPtr requiredSize,                                        // null
     [MarshalAs(UnmanagedType.AsAny)] object deviceInfoData      // null
     );
Example #8
0
 static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr DeviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,
     int DeviceInterfaceDetailDataSize,
     ref int RequiredSize,
     ref SP_DEVINFO_DATA DeviceInfoData
     );
Example #9
0
        static string GetInstanceIDFromDevicePath(string targetDevicePath)
        {
            Guid MonitorGUID = new Guid("E6F07B5F-EE97-4a90-B076-33F57BF4EAA7");

            // We start at the "root" of the device tree and look for all
            // devices that match the interface GUID of a monitor
            IntPtr h = SetupDiGetClassDevs(ref MonitorGUID, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));

            if (h.ToInt64() != INVALID_HANDLE_VALUE)
            {
                bool Success = true;
                uint i       = 0;
                while (Success)
                {
                    // create a Device Interface Data structure
                    SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA();
                    dia.cbSize = (int)Marshal.SizeOf(dia);

                    // start the enumeration
                    Success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref MonitorGUID, i, ref dia);
                    if (Success)
                    {
                        // build a DevInfo Data structure
                        SP_DEVINFO_DATA da = new SP_DEVINFO_DATA();
                        da.cbSize = (uint)Marshal.SizeOf(da);

                        // build a Device Interface Detail Data structure
                        SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                        didd.cbSize = (int)(4 + Marshal.SystemDefaultCharSize); // trust me :)

                        // now we can get some more detailed information
                        uint nRequiredSize = 0;
                        uint nBytes        = BUFFER_SIZE;
                        if (SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nBytes, ref nRequiredSize, ref da))
                        {
                            // Now we get the InstanceID
                            IntPtr ptrInstanceBuf = Marshal.AllocHGlobal((int)nBytes);
                            CM_Get_Device_ID(da.devInst, ptrInstanceBuf, (int)nBytes, 0);
                            string InstanceID = Marshal.PtrToStringAuto(ptrInstanceBuf);
                            //Console.WriteLine("InstanceID: {0}", InstanceID);
                            Marshal.FreeHGlobal(ptrInstanceBuf);

                            //Console.WriteLine("DevicePath: {0}", didd.DevicePath);


                            if (didd.DevicePath.ToUpper() == targetDevicePath.ToUpper())
                            {
                                return(InstanceID);
                            }
                        }
                        i++;
                    }
                }
            }
            SetupDiDestroyDeviceInfoList(h);
            return(null);
        }
Example #10
0
        public static List <string> GetAllDevices(int?vendorId, int?productId)
        {
            int  index = 0;
            GUID guid  = new GUID();
            var  ret   = new List <string>();

            HidD_GetHidGuid(ref guid);
            IntPtr devicesHandle = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT);
            var    diData        = new SP_DEVICE_INTERFACE_DATA();

            diData.cbSize = Marshal.SizeOf(diData);

            while (SetupDiEnumDeviceInterfaces(devicesHandle, IntPtr.Zero, ref guid, index, ref diData))
            {
                //Get the buffer size
                UInt32 size;
                SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

                // Uh...yeah.
                var diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

                //Get detailed information
                if (SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, ref diDetail, size, out size, IntPtr.Zero))
                {
                    //Get a handle to this device
                    var handle = CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite,
                                            IntPtr.Zero, FileMode.Open, EFileAttributes.Overlapped, IntPtr.Zero);

                    //Get this device's attributes
                    var attrib = new HIDD_ATTRIBUTES();
                    attrib.Size = Marshal.SizeOf(attrib);
                    if (HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
                    {
                        //See if this is one we care about
                        if ((!vendorId.HasValue || ((attrib.VendorID & 0xFFFF) == vendorId.Value)) &&
                            (!productId.HasValue || ((attrib.ProductID & 0xFFFF) == productId.Value)))
                        {
                            ret.Add(diDetail.DevicePath);
                            break;
                        }
                    }

                    //Close the handle
                    handle.Close();
                }

                //Move on
                index++;
            }

            SetupDiDestroyDeviceInfoList(devicesHandle);

            return(ret);
        }
Example #11
0
        int FindKnownHidDevices(ref HID_DEVICE[] HidDevices)
        {
            int iHIDD;
            int RequiredLength;

            Guid hidGuid = new Guid();
            SP_DEVICE_INTERFACE_DATA        deviceInfoData          = new SP_DEVICE_INTERFACE_DATA();
            SP_DEVICE_INTERFACE_DETAIL_DATA functionClassDeviceData = new SP_DEVICE_INTERFACE_DETAIL_DATA();

            HidD_GetHidGuid(ref hidGuid);

            //
            // Open a handle to the plug and play dev node.
            //
            SetupDiDestroyDeviceInfoList(hardwareDeviceInfo);
            hardwareDeviceInfo    = SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
            deviceInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));

            iHIDD = 0;
            while (SetupDiEnumDeviceInterfaces(hardwareDeviceInfo, IntPtr.Zero, ref hidGuid, iHIDD, ref deviceInfoData))
            {
                RequiredLength = 0;

                //
                // allocate a function class device data structure to receive the
                // goods about this particular device.
                //
                SetupDiGetDeviceInterfaceDetail(hardwareDeviceInfo, ref deviceInfoData, IntPtr.Zero, 0, ref RequiredLength, IntPtr.Zero);

                if (IntPtr.Size == 8)
                {
                    functionClassDeviceData.cbSize = 8;
                }
                else if (IntPtr.Size == 4)
                {
                    functionClassDeviceData.cbSize = 5;
                }

                //
                // Retrieve the information from Plug and Play.
                //
                SetupDiGetDeviceInterfaceDetail(hardwareDeviceInfo, ref deviceInfoData, ref functionClassDeviceData, RequiredLength, ref RequiredLength, IntPtr.Zero);

                //
                // Open device with just generic query abilities to begin with
                //
                OpenHidDevice(functionClassDeviceData.DevicePath, ref HidDevices, iHIDD);

                iHIDD++;
            }

            return(iHIDD);
        }
Example #12
0
        private void UsBMethod(int index)
        {
            HidD_GetHidGuid(ref guidHID);
            hDevInfo = SetupDiGetClassDevs(ref guidHID, 0, IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE);
            int       bufferSize    = 0;
            ArrayList HIDUSBAddress = new ArrayList();

            //while (true)
            //{
            //获取设备,true获取到

            SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();

            DeviceInterfaceData.cbSize = Marshal.SizeOf(DeviceInterfaceData);

            //for (int i = 0;i < 3;i++)
            //{
            bool result = SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guidHID, (UInt32)index, ref DeviceInterfaceData);
            //}

            //第一次调用出错,但可以返回正确的Size
            SP_DEVINFO_DATA strtInterfaceData = new SP_DEVINFO_DATA();

            result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, strtInterfaceData);

            //第二次调用传递返回值,调用即可成功
            IntPtr detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
            SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();

            detailData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
            Marshal.StructureToPtr(detailData, detailDataBuffer, false);

            result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, strtInterfaceData);
            if (result == false)
            {
                //break;
            }

            //获取设备路径访
            IntPtr pdevicePathName = (IntPtr)((int)detailDataBuffer + 4);
            string devicePathName  = Marshal.PtrToStringAuto(pdevicePathName);

            HIDUSBAddress.Add(devicePathName);

            //index++;
            //break;
            //}


            //连接设备文件
            int  aa = CT_CreateFile(devicePathName);
            bool bb = USBDataRead(HidHandle);
        }
Example #13
0
File: HID.cs Project: NSDN/NSMIA
            /// <summary>
            /// 获取所有连接的hid的设备路径
            /// </summary>
            /// <returns>包含每个设备路径的字符串数组</returns>
            public static void GetHidDeviceList(ref List <string> deviceList)
            {
                Guid hUSB  = Guid.Empty;
                uint index = 0;

                Debug.WriteLine("清除上一次的设备列表.");
                deviceList.Clear();
                Debug.WriteLine("清除Ok.");
                Debug.WriteLine("开始获取HID设备全局ID.");
                // 取得hid设备全局id
                HidD_GetHidGuid(ref hUSB);
                Debug.WriteLine("获取HID设备全局ID OK.");
                Debug.WriteLine("GUID: " + hUSB);
                //取得一个包含所有HID接口信息集合的句柄
                IntPtr hidInfoSet = SetupDiGetClassDevs(ref hUSB, 0, IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE);

                if (hidInfoSet != IntPtr.Zero)
                {
                    SP_DEVICE_INTERFACE_DATA interfaceInfo = new SP_DEVICE_INTERFACE_DATA();
                    interfaceInfo.cbSize = Marshal.SizeOf(interfaceInfo);
                    //查询集合中每一个接口
                    Debug.WriteLine("查询HID详细接口信息.");
                    for (index = 0; index < MAX_USB_DEVICES; index++)
                    {
                        //得到第index个接口信息
                        if (SetupDiEnumDeviceInterfaces(hidInfoSet, IntPtr.Zero, ref hUSB, index, ref interfaceInfo))
                        {
                            int buffsize = 0;
                            // 取得接口详细信息:第一次读取错误,但可以取得信息缓冲区的大小
                            SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, IntPtr.Zero, buffsize, ref buffsize, null);
                            //构建接收缓冲
                            IntPtr pDetail = Marshal.AllocHGlobal(buffsize);
                            SP_DEVICE_INTERFACE_DETAIL_DATA detail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                            detail.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                            Marshal.StructureToPtr(detail, pDetail, false);
                            if (SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, pDetail, buffsize, ref buffsize, null))
                            {
                                Debug.WriteLine("往deviceList  " + index + 1 + " 中加入HID详细接口信息. " + (Marshal.PtrToStringAuto((IntPtr)((int)pDetail + 4))));
                                deviceList.Add(Marshal.PtrToStringAuto((IntPtr)((int)pDetail + 4)));
                            }
                            Marshal.FreeHGlobal(pDetail);
                        }
                        //else
                        //    Debug.WriteLine("查询第 " + index + " 个HID设备接口信息." + SetupDiEnumDeviceInterfaces(hidInfoSet, IntPtr.Zero, ref hUSB, index, ref interfaceInfo));
                    }
                }
                SetupDiDestroyDeviceInfoList(hidInfoSet);
                //return deviceList.ToArray();
            }
    public static ReadOnlyCollection <USBController> GetHostControllers()
    {
        List <USBController> list = new List <USBController>();
        Guid   guid          = new Guid("3abf6f2d-71c4-462a-8a92-1e6861e6af27");
        IntPtr deviceInfoSet = Acer_USB_Library.SetupDiGetClassDevs(ref guid, 0, IntPtr.Zero, 18);

        if (deviceInfoSet.ToInt32() != -1)
        {
            IntPtr intPtr = Marshal.AllocHGlobal(2048);
            int    num    = 0;
            bool   flag;
            do
            {
                USBController uSBController = new USBController();
                uSBController.ControllerIndex = num;
                SP_DEVICE_INTERFACE_DATA structure = default(SP_DEVICE_INTERFACE_DATA);
                structure.cbSize = Marshal.SizeOf(structure);
                flag             = Acer_USB_Library.SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref guid, num, ref structure);
                if (flag)
                {
                    SP_DEVINFO_DATA structure2 = default(SP_DEVINFO_DATA);
                    structure2.cbSize = Marshal.SizeOf(structure2);
                    SP_DEVICE_INTERFACE_DETAIL_DATA sP_DEVICE_INTERFACE_DETAIL_DATA = default(SP_DEVICE_INTERFACE_DETAIL_DATA);
                    sP_DEVICE_INTERFACE_DETAIL_DATA.cbSize = 4 + Marshal.SystemDefaultCharSize;
                    int num2 = 0;
                    int deviceInterfaceDetailDataSize = 2048;
                    if (Acer_USB_Library.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref structure, ref sP_DEVICE_INTERFACE_DETAIL_DATA, deviceInterfaceDetailDataSize, ref num2, ref structure2))
                    {
                        uSBController.ControllerDevicePath = sP_DEVICE_INTERFACE_DETAIL_DATA.DevicePath;
                        int num3 = 0;
                        int num4 = 1;
                        if (Acer_USB_Library.SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref structure2, 0, ref num4, intPtr, 2048, ref num3))
                        {
                            uSBController.ControllerDeviceDesc = Marshal.PtrToStringAuto(intPtr);
                        }
                        if (Acer_USB_Library.SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref structure2, 9, ref num4, intPtr, 2048, ref num3))
                        {
                            uSBController.ControllerDriverKeyName = Marshal.PtrToStringAuto(intPtr);
                        }
                    }
                    list.Add(uSBController);
                }
                num++;
            }while (flag);
            Marshal.FreeHGlobal(intPtr);
            Acer_USB_Library.SetupDiDestroyDeviceInfoList(deviceInfoSet);
        }
        return(new ReadOnlyCollection <USBController>(list));
    }
Example #15
0
        public static unsafe string SetupDiGetDeviceInterfaceDetail(
            SafeDeviceInfoSetHandle deviceInfoSet,
            SP_DEVICE_INTERFACE_DATA interfaceData,
            SP_DEVINFO_DATA *deviceInfoData)
        {
            int requiredSize;

            // First call to get the size to allocate
            SetupDiGetDeviceInterfaceDetail(
                deviceInfoSet,
                ref interfaceData,
                null,
                0,
                &requiredSize,
                deviceInfoData);

            // As we passed an empty buffer we know that the function will fail, not need to check the result.
            var lastError = GetLastError();

            if (lastError != Win32ErrorCode.ERROR_INSUFFICIENT_BUFFER)
            {
                throw new Win32Exception(lastError);
            }

            fixed(byte *pBuffer = new byte[requiredSize])
            {
                var pDetail = (SP_DEVICE_INTERFACE_DETAIL_DATA *)pBuffer;

                pDetail->cbSize = SP_DEVICE_INTERFACE_DETAIL_DATA.ReportableStructSize;

                // Second call to get the value
                var success = SetupDiGetDeviceInterfaceDetail(
                    deviceInfoSet,
                    ref interfaceData,
                    pDetail,
                    requiredSize,
                    null,
                    null);

                if (!success)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                    return(null);
                }

                return(SP_DEVICE_INTERFACE_DETAIL_DATA.GetDevicePath(pDetail));
            }
        }
        public string GetDevicePath()
        {
            Guid   deviceGuid = new Guid("573E8C73-0CB4-4471-A1BF-FAB26C31D384");
            IntPtr DeviceInfo = SetupDiGetClassDevs(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));

            if (DeviceInfo == (IntPtr)(-1))
            {
                Console.WriteLine("SetupDiGetClassDevs Failed");
                return("");
            }

            SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();

            deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);

            bool result = SetupDiEnumDeviceInterfaces(DeviceInfo, IntPtr.Zero, ref deviceGuid, 0, ref deviceInterfaceData);

            if (!result)
            {
                Console.WriteLine("SetupDiEnumDeviceInterfaces Failed");
                SetupDiDestroyDeviceInfoList(DeviceInfo);
                return("");
            }

            uint requiredSize = 0;


            SetupDiGetDeviceInterfaceDetail(DeviceInfo, ref deviceInterfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
            SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();

            if (requiredSize < Marshal.SizeOf(didd))
            {
                didd.cbSize = 8;  //Test for 64bit
                uint length = requiredSize;
                result = SetupDiGetDeviceInterfaceDetail(DeviceInfo, ref deviceInterfaceData, ref didd, length, out requiredSize, IntPtr.Zero);
            }

            Console.WriteLine("NameLength = " + didd.DevicePath.Length);
            Console.WriteLine("Name = " + didd.DevicePath);

            SetupDiDestroyDeviceInfoList(DeviceInfo);
            if (!result)
            {
                return("\\\\?\\usb#vid_1603&pid_0002&mi_01#6&b8aa88a&0&0001#{573e8c73-0cb4-4471-a1bf-fab26c31d384}");
            }

            return(didd.DevicePath);
        }
Example #17
0
        public static List <USBDevice> GetDeviceByGuid(Guid guid)
        {
            List <USBDevice> deviceList = new List <USBDevice>();
            IntPtr           info       = GetClassDevOfHandle(guid);

            if (info == IntPtr.Zero)
            {
                return(deviceList);
            }
            uint index = 0;
            SP_DEVICE_INTERFACE_DATA ifData = new SP_DEVICE_INTERFACE_DATA();

            ifData.cbSize = Marshal.SizeOf(ifData);

            for (index = 0; GetEnumDeviceInterfaces(info, ref guid, index, ref ifData); ++index)
            {
                uint needed = 0;
                GetDeviceInterfaceDetail(info, ref ifData, IntPtr.Zero, 0, ref needed, null);
                IntPtr pDetail = Marshal.AllocHGlobal((int)needed);
                SP_DEVICE_INTERFACE_DETAIL_DATA detail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                detail.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                Marshal.StructureToPtr(detail, pDetail, false);
                SP_DEVINFO_DATA did    = new SP_DEVINFO_DATA();
                USBDevice       device = null;
                if (GetDeviceInterfaceDetail(info, ref ifData, pDetail, needed, ref needed, did))
                {
                    device = new USBDevice((Marshal.PtrToStringAuto((IntPtr)((int)pDetail + 4))));
                }
                StringBuilder Product = new StringBuilder();
                uint          reqsize = 0;
                if (GetDeviceRegistryProperty(info, did, SPDRP_DEVICEDESC, 0, Product, 253, ref reqsize))
                {
                    device.Name = Product.ToString();
                }
                else
                {
                    device.Name = ("(Unnamed device)");
                }
                Marshal.FreeHGlobal(pDetail);
                deviceList.Add(device);
            }
            DestroyDeviceInfoList(info);

            return(deviceList);
        }
Example #18
0
        static bool isGpuRemovable(string pnpDeviceID)
        {
            Guid   gpuGuid = new Guid("{5b45201d-f2f2-4f3b-85bb-30ff1f953599}"); // GUID_DEVINTERFACE_DISPLAY_ADAPTER
            IntPtr h       = SetupDiGetClassDevs(IntPtr.Zero, pnpDeviceID, IntPtr.Zero, (uint)(DiGetClassFlags.DIGCF_ALLCLASSES | DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));

            if (h == INVALID_HANDLE_VALUE)
            {
                return(false);
            }

            try {
                for (uint i = 0; ; i++)
                {
                    SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA();
                    interfaceData.cbSize = Marshal.SizeOf(interfaceData);
                    if (!SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref gpuGuid, i, ref interfaceData))
                    {
                        break;
                    }

                    SP_DEVINFO_DATA devinfoData = new SP_DEVINFO_DATA();
                    devinfoData.cbSize = (uint)Marshal.SizeOf(devinfoData);

                    SP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                    interfaceDetailData.cbSize = (IntPtr.Size == 4) ? 4 + Marshal.SystemDefaultCharSize : 8;

                    uint nRequiredSize = 0;
                    uint nBytes        = BUFFER_SIZE;
                    if (!SetupDiGetDeviceInterfaceDetail(h, ref interfaceData, ref interfaceDetailData, nBytes, ref nRequiredSize, ref devinfoData))
                    {
                        break;
                    }

                    uint removalPolicy = getDWORDProp(h, devinfoData, SetupDiGetDeviceRegistryPropertyEnum.SPDRP_REMOVAL_POLICY);
                    if (removalPolicy != (uint)RemovalPolicy.CM_REMOVAL_POLICY_EXPECT_NO_REMOVAL)
                    {
                        return(true);
                    }
                }
            } finally {
                SetupDiDestroyDeviceInfoList(h);
            }

            return(false);
        }
        public string GetDevicePath(Guid classGuid)
        {
            IntPtr hDevInfo = IntPtr.Zero;
            try
            {
                hDevInfo = SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, DiGetClassFlags.DIGCF_DEVICEINTERFACE | DiGetClassFlags.DIGCF_PRESENT);

                if (hDevInfo.ToInt64() <= 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA();
                dia.cbSize = (uint)Marshal.SizeOf(dia);

                SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA();
                devInfo.cbSize = (UInt32)Marshal.SizeOf(devInfo);

                UInt32 i = 0;

                // start the enumeration
                if (!SetupDiEnumDeviceInterfaces(hDevInfo, null, ref classGuid, i, dia))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                didd.cbSize = 4 + Marshal.SystemDefaultCharSize; // trust me :)

                UInt32 requiredSize = 0;

                if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, dia, ref didd, 256, out requiredSize, devInfo))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return didd.DevicePath;

            }
            finally
            {
                SetupDiDestroyDeviceInfoList(hDevInfo);
            }
        }
Example #20
0
        private Tuple <string, string> GetDeviceName(IntPtr hDevInfo, ref SP_DEVICE_INTERFACE_DATA interfaceData)
        {
            uint            requiredSize = 0;
            string          deviceName   = null;
            string          friendlyName = null;
            SP_DEVINFO_DATA infoData     = new SP_DEVINFO_DATA();

            infoData.cbSize = Marshal.SizeOf(infoData);

            //get size first
            SetupDiGetDeviceInterfaceDetail(hDevInfo, ref interfaceData, IntPtr.Zero, 0, ref requiredSize, ref infoData /*infoData*/);
            IntPtr detailDataBuffer = Marshal.AllocHGlobal((int)requiredSize);

            if (detailDataBuffer != IntPtr.Zero)
            {
                // get dev name now.
                SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                detailData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                Marshal.StructureToPtr(detailData, detailDataBuffer, false);

                if (SetupDiGetDeviceInterfaceDetail(hDevInfo, ref interfaceData, detailDataBuffer, requiredSize, ref requiredSize, ref infoData))
                {
                    IntPtr pdevicePathName = (IntPtr)((int)detailDataBuffer + 4);
                    deviceName = Marshal.PtrToStringAuto(pdevicePathName);

                    uint regDataType = 0;

                    // get size for friendly name
                    SetupDiGetDeviceRegistryProperty(hDevInfo, ref infoData, SPDRP_FRIENDLYNAME,
                                                     ref regDataType, IntPtr.Zero, 0, ref requiredSize);
                    IntPtr nameBuffer = Marshal.AllocHGlobal((int)requiredSize);
                    if (SetupDiGetDeviceRegistryProperty(hDevInfo, ref infoData, SPDRP_FRIENDLYNAME,
                                                         ref regDataType, nameBuffer, requiredSize, ref requiredSize))
                    {
                        friendlyName = Marshal.PtrToStringAuto(nameBuffer);
                    }
                    Marshal.FreeHGlobal(nameBuffer);
                    nameBuffer = IntPtr.Zero;
                }
                Marshal.FreeHGlobal(detailDataBuffer);
                detailDataBuffer = IntPtr.Zero;
            }
            return(new Tuple <string, string>(deviceName, friendlyName));
        }
Example #21
0
        internal static IEnumerable <DeviceMetaData> EnumerableDeviceMetaData(Guid classGuid)
        {
            using (var hostHandles = SetupDiGetClassDevs(
                       ref classGuid,
                       IntPtr.Zero,
                       IntPtr.Zero,
                       DIGCF_PRESENT | DIGCF_DEVICEINTERFACE))
            {
                var deviceInstace = new SP_DEVICE_INTERFACE_DATA();
                deviceInstace.cbSize = Marshal.SizeOf(deviceInstace);

                for (int deviceIndex = 0;
                     SetupDiEnumDeviceInterfaces(
                         hostHandles, IntPtr.Zero, ref classGuid,
                         deviceIndex, ref deviceInstace);
                     deviceIndex++)
                {
                    var deviceInterfaceDetailDataSize =
                        GetDeviceInterfaceDetailDataSize(hostHandles, ref deviceInstace);
                    var deviceInstaceDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA
                    {
                        cbSize = IntPtr.Size == 4 ? 4 + Marshal.SystemDefaultCharSize : 8
                    };

                    var deviceInfoData = new SP_DEVINFO_DATA {
                        cbSize = Marshal.SizeOf <SP_DEVINFO_DATA>()
                    };
                    if (SetupDiGetDeviceInterfaceDetail(
                            hostHandles,
                            ref deviceInstace,
                            ref deviceInstaceDetail,
                            deviceInterfaceDetailDataSize,
                            ref deviceInterfaceDetailDataSize,
                            ref deviceInfoData))
                    {
                        yield return(new DeviceMetaData(
                                         GetDeviceProperty(SPDRP_DEVICEDESC, hostHandles, deviceInfoData),
                                         GetDeviceProperty(SPDRP_DRIVER, hostHandles, deviceInfoData),
                                         deviceInstaceDetail.DevicePath));
                    }
                }
            }
        }
Example #22
0
        private string Getbatterypath()
        {
            IntPtr hdev;
            SP_DEVICE_INTERFACE_DATA        did  = new SP_DEVICE_INTERFACE_DATA();
            SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            uint cbReq = 0;
            int  err   = 0;

            did.cbSize  = Marshal.SizeOf(did);
            didd.cbSize = /*Marshal.SizeOf(didd)*/ 4 + Marshal.SystemDefaultCharSize;
            hdev        = SetupDiGetClassDevs(ref GUID_DEVICE_BATTERY, "", IntPtr.Zero, 0x2 | 0x10);
            err         = Marshal.GetLastWin32Error();
            SetupDiEnumDeviceInterfaces(hdev, IntPtr.Zero, ref GUID_DEVICE_BATTERY, 1, ref did);
            err = Marshal.GetLastWin32Error();
            SetupDiGetDeviceInterfaceDetail(hdev, ref did, IntPtr.Zero, 0, ref cbReq, IntPtr.Zero);
            err = Marshal.GetLastWin32Error();
            SetupDiGetDeviceInterfaceDetail(hdev, ref did, ref didd, cbReq, ref cbReq, IntPtr.Zero);
            err = Marshal.GetLastWin32Error();
            return(didd.DevicePath.Substring(0));
        }
Example #23
0
        public static bool SetupDiGetDeviceInterfaceDetail(HDEVINFO deviceInfoSet,
                                                           ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
                                                           out SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData)
        {
            deviceInterfaceDetailData = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA();

            deviceInterfaceDetailData.Size = IntPtr.Size == 8 ? 8 : (4 + Marshal.SystemDefaultCharSize);

            if (NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet,
                                                              ref deviceInterfaceData, ref deviceInterfaceDetailData,
                                                              Marshal.SizeOf(deviceInterfaceDetailData) - 4, IntPtr.Zero, IntPtr.Zero))
            {
                return(true);
            }
            else
            {
                deviceInterfaceDetailData = default(SP_DEVICE_INTERFACE_DETAIL_DATA);
                return(false);
            }
        }
Example #24
0
        public KeyboardController()
        {
            // Get HID GUID.
            Hid.HidD_GetHidGuid(out Guid hidGuid);

            List <HidDevice> devs      = new List <HidDevice>();
            IntPtr           classDevs = SetupApi.SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, DiGetClassFlags.Present | DiGetClassFlags.DeviceInterface);

            try
            {
                // Enumerate HID devices.
                for (uint index = 0;; ++index)
                {
                    SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA {
                        cbSize = (uint)Marshal.SizeOf <SP_DEVICE_INTERFACE_DATA>()
                    };
                    if (!SetupApi.SetupDiEnumDeviceInterfaces(classDevs, IntPtr.Zero, ref hidGuid, index, ref deviceInterfaceData))
                    {
                        break;                         // End of list.
                    }
                    SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA {
                        cbSize = IntPtr.Size == 8 ? 8U : (uint)(4 + Marshal.SystemDefaultCharSize)
                    };
                    SP_DEVINFO_DATA deviceInfoData = new SP_DEVINFO_DATA {
                        cbSize = (uint)Marshal.SizeOf <SP_DEVINFO_DATA>()
                    };
                    if (SetupApi.SetupDiGetDeviceInterfaceDetail(classDevs, ref deviceInterfaceData, ref deviceInterfaceDetailData, 256U, out uint requiredSize, ref deviceInfoData))
                    {
                        // Found one.
                        // Try to open device.
                        string         devPath   = deviceInterfaceDetailData.DevicePath;
                        SafeFileHandle devHandle = Kernel32.CreateFile(devPath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE,
                                                                       Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE, IntPtr.Zero, Kernel32.CREATE_NEW | Kernel32.CREATE_ALWAYS, Kernel32.FILE_FLAG_OVERLAPPED, IntPtr.Zero);

                        // Get HID attributes.
                        HIDD_ATTRIBUTES attributes = default;
                        HIDP_CAPS       caps;
                        Hid.HidD_GetAttributes(devHandle, ref attributes);

                        // Match against Gigabyte keyboard product IDs.
                        if (!supportedKeyboards.TryGetValue(attributes.VendorID, out ushort[] pids))
Example #25
0
        /// <summary>
        /// 获取所有连接的hid的设备路径
        /// </summary>
        /// <returns>包含每个设备路径的字符串数组</returns>
        public static void GetHidDeviceList(List <string> deviceList)
        {
            Guid hUSB = Guid.Empty;

            uint index = 0;

            deviceList.Clear();
            //01 取得hid设备全局id
            HidD_GetHidGuid(ref hUSB);
            //02 取得一个包含所有HID接口信息集合的句柄
            IntPtr hidInfoSet = SetupDiGetClassDevs(ref hUSB, 0, IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE);

            if (hidInfoSet != IntPtr.Zero)
            {
                SP_DEVICE_INTERFACE_DATA interfaceInfo = new SP_DEVICE_INTERFACE_DATA();
                interfaceInfo.cbSize = Marshal.SizeOf(interfaceInfo);
                //查询集合中每一个接口
                for (index = 0; index < MAX_USB_DEVICES; index++)
                {
                    //03 得到第index个接口信息,该结构用于识别一个HID设备接口
                    if (SetupDiEnumDeviceInterfaces(hidInfoSet, IntPtr.Zero, ref hUSB, index, ref interfaceInfo))
                    {
                        int buffsize = 0;
                        //04 取得接口详细信息:第一次读取错误,但可以取得信息缓冲区的大小,获得一个指向该设备的路径名
                        SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, IntPtr.Zero, buffsize, ref buffsize, null);
                        //构建接收缓冲
                        IntPtr pDetail = Marshal.AllocHGlobal(buffsize);
                        SP_DEVICE_INTERFACE_DETAIL_DATA detail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                        detail.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                        Marshal.StructureToPtr(detail, pDetail, false);

                        if (SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, pDetail, buffsize, ref buffsize, null))
                        {
                            deviceList.Add(Marshal.PtrToStringAuto((IntPtr)((int)pDetail + 4)));
                        }
                        Marshal.FreeHGlobal(pDetail);
                    }
                }
            }
            SetupDiDestroyDeviceInfoList(hidInfoSet);
        }
Example #26
0
        private static string GetDevicePath(IntPtr deviceInfoList, SP_DEVICE_INTERFACE_DATA deviceInterfaceData)
        {
            try
            {
                //Get the buffer size
                int bufferSize = 0;
                SetupDiGetDeviceInterfaceDetail(deviceInfoList, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero);
                SP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA
                {
                    Size = IntPtr.Size == 4 ? 4 + Marshal.SystemDefaultCharSize : 8
                };

                //Read device details
                if (SetupDiGetDeviceInterfaceDetail(deviceInfoList, ref deviceInterfaceData, ref interfaceDetail, bufferSize, ref bufferSize, IntPtr.Zero))
                {
                    if (!string.IsNullOrWhiteSpace(interfaceDetail.DevicePath))
                    {
                        return(interfaceDetail.DevicePath.ToLower());
                    }
                    else
                    {
                        Debug.WriteLine("Failed to get device path, empty string.");
                        return(string.Empty);
                    }
                }
                else
                {
                    Debug.WriteLine("Failed to get device path, detail missing.");
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to get device path: " + ex.Message);
                return(string.Empty);
            }
        }
Example #27
0
        //*************************************************************
        //* Open One USB Device
        //*************************************************************
        private static SafeFileHandle OpenOneDevice(IntPtr HardwareDeviceInfo, SP_DEVICE_INTERFACE_DATA DeviceInfoData,
                                                    ref string devName)
        {
            var            functionClassDeviceData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            var            devinfo         = IntPtr.Zero;
            uint           predictedLength = 0;
            uint           requiredLength  = 0;
            SafeFileHandle hOut;

            SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, ref DeviceInfoData, IntPtr.Zero, 0, out requiredLength,
                                            IntPtr.Zero);
            predictedLength = requiredLength;
            functionClassDeviceData.DevicePath = "";
            requiredLength = 0;
            if (IntPtr.Size == 8) // 64-bit
            {
                functionClassDeviceData.cbSize = 8;
            }
            else // 32-bit
            {
                functionClassDeviceData.cbSize = 4 + 1;
            }

            if (!SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, ref DeviceInfoData, ref functionClassDeviceData,
                                                 predictedLength, out requiredLength, IntPtr.Zero))
            {
                if (!SetupDiGetDeviceInterfaceDetail(HardwareDeviceInfo, ref DeviceInfoData,
                                                     ref functionClassDeviceData, predictedLength, out requiredLength, IntPtr.Zero))
                {
                    return(new SafeFileHandle(new IntPtr(-1), true));
                }
            }
            devName = functionClassDeviceData.DevicePath;
            hOut    = CreateFile(functionClassDeviceData.DevicePath, GENERIC_READ | GENERIC_WRITE,
                                 FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
            return(hOut);
        }
        private static string GetDevicePath(
            IntPtr deviceInfoSet,
            SP_DEVICE_INTERFACE_DATA deviceInterfaceData)
        {
            string result     = null;
            var    bufferSize = 0;

            var interfaceDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA
            {
                Size = IntPtr.Size == 4 ? 4 + Marshal.SystemDefaultCharSize : 8
            };

            SetupDiGetDeviceInterfaceDetailBuffer(deviceInfoSet,
                                                  ref deviceInterfaceData,
                                                  IntPtr.Zero,
                                                  0,
                                                  ref bufferSize,
                                                  IntPtr.Zero);

            if (bufferSize > 0)
            {
                if (SetupDiGetDeviceInterfaceDetail(deviceInfoSet,
                                                    ref deviceInterfaceData,
                                                    ref interfaceDetail,
                                                    bufferSize,
                                                    ref bufferSize,
                                                    IntPtr.Zero))
                {
                    result = string.IsNullOrEmpty(interfaceDetail.DevicePath)
                         ? null
                         : interfaceDetail.DevicePath;
                }
            }

            return(result);
        }
Example #29
0
 public static extern unsafe bool SetupDiGetDeviceInterfaceDetail(
     SafeDeviceInfoSetHandle deviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     SP_DEVICE_INTERFACE_DETAIL_DATA* deviceInterfaceDetailData,
     int deviceInterfaceDetailDataSize,
     int* requiredSize,
     SP_DEVINFO_DATA deviceInfoData);
Example #30
0
        public static List <StorageDeviceInfo> GetRemovableDriveDeviceIds(DriveType driveType, DeviceType deviceType)
        {
            List <StorageDeviceInfo> devices = new List <StorageDeviceInfo>();

            if (driveType == DriveType.Removable && deviceType == DeviceType.FILE_DEVICE_DISK)
            {
                var guid = Win32Constants.GUID_DEVINTERFACE_DISK;

                var setupInterfaceResult = NativeMethods.SetupDiGetClassDevs(
                    ref guid,
                    null,
                    IntPtr.Zero,
                    DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE);
                if (setupInterfaceResult == Win32Constants.INVALID_HANDLE_VALUE)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }

                bool result = true;
                uint i      = 0;
                while (result)
                {
                    SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA();
                    dia.cbSize = (uint)Marshal.SizeOf(dia);

                    result = NativeMethods.SetupDiEnumDeviceInterfaces(setupInterfaceResult, IntPtr.Zero, ref guid, i, out dia);
                    i++;

                    if (result)
                    {
                        SP_DEVINFO_DATA da = new SP_DEVINFO_DATA();
                        da.cbSize = (uint)Marshal.SizeOf(da);
                        var daPtr = Win32Utils.AllocateStructToPointer <SP_DEVINFO_DATA>(da).Item1;

                        SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                        if (IntPtr.Size == 8)
                        {
                            didd.cbSize = 8;
                        }
                        else
                        {
                            didd.cbSize = (uint)(4 + Marshal.SystemDefaultCharSize);
                        }
                        var diddPtr = Win32Utils.AllocateStructToPointer(didd).Item1;

                        if (!NativeMethods.SetupDiGetDeviceInterfaceDetail(
                                setupInterfaceResult,
                                ref dia,
                                diddPtr,
                                Win32Constants.SIZE_OUTPUT,
                                out uint requireSize,
                                daPtr))
                        {
                            Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                        }

                        da   = Marshal.PtrToStructure <SP_DEVINFO_DATA>(daPtr);
                        didd = Marshal.PtrToStructure <SP_DEVICE_INTERFACE_DETAIL_DATA>(diddPtr);

                        string instanceID;
                        var    getParentResult = NativeMethods.CM_Get_Parent(out IntPtr ptrPrevious, da.devInst, 0);
                        if (getParentResult != Win32Constants.CR_SUCCESS)
                        {
                            instanceID = getParentResult.ToString();
                        }
                        else
                        {
                            IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(Win32Constants.SIZE_OUTPUT);

                            var getDeviceIdResult = NativeMethods.CM_Get_Device_ID(ptrPrevious, ptrInstanceBuf, Win32Constants.SIZE_OUTPUT, 0);
                            if (getDeviceIdResult != Win32Constants.CR_SUCCESS)
                            {
                                instanceID = getDeviceIdResult.ToString();
                            }
                            else
                            {
                                instanceID = Marshal.PtrToStringAuto(ptrInstanceBuf);

                                using (SafeFileHandle handle = CreateDeviceNoRightsHandle(didd.DevicePath))
                                {
                                    var deviceNumber = Win32Utils.DeviceIoControlAction <STORAGE_DEVICE_NUMBER>(handle, DeviceControlCode.STORAGE_GET_DEVICE_NUMBER);

                                    StorageDeviceInfo info = new StorageDeviceInfo
                                    {
                                        StorageDeviceNumber    = deviceNumber.Item1,
                                        StorageDeviceNumberRaw = deviceNumber.Item2,
                                        InstanceID             = instanceID,
                                        DevicePath             = didd.DevicePath
                                    };

                                    devices.Add(info);
                                }
                            }

                            Marshal.FreeHGlobal(daPtr);
                            Marshal.FreeHGlobal(diddPtr);
                            Marshal.FreeHGlobal(ptrInstanceBuf);
                        }
                    }
                }

                if (!NativeMethods.SetupDiDestroyDeviceInfoList(setupInterfaceResult))
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }

            return(devices);
        }
        //Metodo de ayuda para encontrar la ruta al dispositivo que se busca, esta funcion es llamada desde el metodo "EncuentraDevHID"
        private string GetDevicePath(IntPtr Infoset, ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData)
        {
            uint nRequiredSize = 0;
            //Para obtener la ruta del dispositivo se hace un proceso de dos pasos, llamar a SetupDiGetDeviceInterfaceDetail la primer vez para obtener el espacio a guardar en cSize
            //Llamar por segunda vez a la misma funcion para obtener la ruta del dispositivo.
            if (!SetupDiGetDeviceInterfaceDetail(Infoset, ref DeviceInterfaceData, IntPtr.Zero, 0, ref nRequiredSize, IntPtr.Zero))//Primera llamada
            {
                SP_DEVICE_INTERFACE_DETAIL_DATA dDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();

                if (IntPtr.Size == 8) // for 64 bit operating systems
                {
                    dDetail.cbSize = 8;
                }
                else
                {
                    dDetail.cbSize = 5; // for 32 bit systems
                }

                if (SetupDiGetDeviceInterfaceDetail(Infoset, ref DeviceInterfaceData, ref dDetail, nRequiredSize, ref nRequiredSize, IntPtr.Zero)) //Segunda llamada
                {
                    return dDetail.DevicePath;//Listo se encontro la ruta de algun dispositivo, falta ahora ver si coinciden VIP y PID
                }
                string error = Marshal.GetLastWin32Error().ToString();
            }
            return null; //No se encontro ningun otro dispositivo en la lista :(
        }
	    static internal extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData, int deviceInterfaceDetailDataSize, ref int requiredSize, IntPtr deviceInfoData);
        /// <summary>
        /// C Code by http://www.reddit.com/user/chrisgzy
        /// Converted to C# by http://www.reddit.com/user/billism
        /// </summary>
        private IntPtr GetDeviceHandle(uint uiVID, uint uiPID, uint uiMI)
        {
            IntPtr deviceInfo = SetupDiGetClassDevs(ref GUID_DEVINTERFACE_HID, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
            if (deviceInfo.ToInt64() == INVALID_HANDLE_VALUE)
            {
                return IntPtr.Zero;
            }

            IntPtr returnPointer = IntPtr.Zero;

            SP_DEVINFO_DATA deviceData = new SP_DEVINFO_DATA();
            deviceData.cbSize = (uint)Marshal.SizeOf(deviceData);

            for (uint i = 0; SetupDiEnumDeviceInfo(deviceInfo, i, ref deviceData); ++i)
            {
                IntPtr deviceId = Marshal.AllocHGlobal(MAX_DEVICE_ID_LEN); // was wchar_t[] type
                // CM_Get_Device_ID was CM_Get_Device_IDW in C++ code
                if (CM_Get_Device_ID(deviceData.devInst, deviceId, MAX_DEVICE_ID_LEN, 0) != 0)
                {
                    continue;
                }

                if (!IsMatchingDevice(deviceId, uiVID, uiPID, uiMI))
                    continue;

                SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA(); // C code used SP_INTERFACE_DEVICE_DATA
                interfaceData.cbSize = (uint)Marshal.SizeOf(interfaceData);

                if (!SetupDiEnumDeviceInterfaces(deviceInfo, ref deviceData, ref GUID_DEVINTERFACE_HID, 0, ref interfaceData))
                {
                    break;
                }

                uint requiredSize = 0;
                SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
                // var lastError = Marshal.GetLastWin32Error();

                SP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                if (IntPtr.Size == 8) // for 64 bit operating systems
                {
                    interfaceDetailData.cbSize = 8;
                }
                else
                {
                    interfaceDetailData.cbSize = 4 + (uint)Marshal.SystemDefaultCharSize; // for 32 bit systems
                }

                if (!SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, ref interfaceDetailData, requiredSize, IntPtr.Zero, IntPtr.Zero))
                {
                    break;
                }

                var deviceHandle = CreateFile(interfaceDetailData.DevicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, IntPtr.Zero);
                if (deviceHandle.ToInt64() == INVALID_HANDLE_VALUE)
                {
                    break;
                }

                returnPointer = deviceHandle;
                break;
            }

            SetupDiDestroyDeviceInfoList(deviceInfo);
            return returnPointer;
        }
        /// <summary>
        /// Get Device data for the given device number
        /// </summary>
        /// <param name="DeviceNumber">Device number</param>
        /// <returns>Deice data</returns>
        private static SP_DEVINFO_DATA GetDevInfoForDeviceNumber(long DeviceNumber)
        {
            SP_DEVINFO_DATA result = null;
            Guid            guid   = new Guid(GUID_DEVINTERFACE_DISK);

            IntPtr _deviceInfoSet = SetupDiGetClassDevs(ref guid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

            if (_deviceInfoSet.ToInt32() == INVALID_HANDLE_VALUE)
            {
                return(result);
            }
            int index = 0;

            while (true)
            {
                SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA();

                if (!SetupDiEnumDeviceInterfaces(_deviceInfoSet, null, ref guid, index, interfaceData))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error != ERROR_NO_MORE_ITEMS)
                    {
                        throw new Win32Exception(error);
                    }
                    break;
                }

                SP_DEVINFO_DATA devData = new SP_DEVINFO_DATA();
                int             size    = 0;
                if (!SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, interfaceData, IntPtr.Zero, 0, ref size, devData))
                {
                    int error = Marshal.GetLastWin32Error();
                    if (error != ERROR_INSUFFICIENT_BUFFER)
                    {
                        throw new Win32Exception(error);
                    }
                }

                IntPtr buffer = Marshal.AllocHGlobal(size);
                SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                detailData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                Marshal.StructureToPtr(detailData, buffer, false);

                if (!SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, interfaceData, buffer, size, ref size, devData))
                {
                    Marshal.FreeHGlobal(buffer);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                IntPtr pDevicePath = (IntPtr)((int)buffer + Marshal.SizeOf(typeof(int)));
                string devicePath  = Marshal.PtrToStringAuto(pDevicePath);
                Marshal.FreeHGlobal(buffer);
                if (GetDeviceNumber(devicePath) == DeviceNumber)
                {
                    result = devData;
                    break;
                }

                index++;
            }

            return(result);
        }
Example #35
0
 static extern bool SetupDiGetDeviceInterfaceDetail(
     IntPtr DeviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA DeviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,
     int DeviceInterfaceDetailDataSize,
     ref int RequiredSize,
     ref SP_DEVINFO_DATA DeviceInfoData
 );
Example #36
0
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------
        //-------------------------------------------------------BEGIN CUT AND PASTE BLOCK-----------------------------------------------------------------------------------
        //FUNCTION:	CheckIfPresentAndGetUSBDevicePath()
        //PURPOSE:	Check if a USB device is currently plugged in with a matching VID and PID
        //INPUT:	Uses globally declared String DevicePath, globally declared GUID, and the MY_DEVICE_ID constant.
        //OUTPUT:	Returns BOOL.  TRUE when device with matching VID/PID found.  FALSE if device with VID/PID could not be found.
        //            When returns TRUE, the globally accessable "DetailedInterfaceDataStructure" will contain the device path
        //            to the USB device with the matching VID/PID.
        bool CheckIfPresentAndGetUSBDevicePath()
        {
            /*
            Before we can "connect" our application to our USB embedded device, we must first find the device.
            A USB bus can have many devices simultaneously connected, so somehow we have to find our device only.
            This is done with the Vendor ID (VID) and Product ID (PID).  Each USB product line should have
            a unique combination of VID and PID.

            Microsoft has created a number of functions which are useful for finding plug and play devices.  Documentation
            for each function used can be found in the MSDN library.  We will be using the following functions (unmanaged C functions):

            SetupDiGetClassDevs()					//provided by setupapi.dll, which comes with Windows
            SetupDiEnumDeviceInterfaces()			//provided by setupapi.dll, which comes with Windows
            GetLastError()							//provided by kernel32.dll, which comes with Windows
            SetupDiDestroyDeviceInfoList()			//provided by setupapi.dll, which comes with Windows
            SetupDiGetDeviceInterfaceDetail()		//provided by setupapi.dll, which comes with Windows
            SetupDiGetDeviceRegistryProperty()		//provided by setupapi.dll, which comes with Windows
            CreateFile()							//provided by kernel32.dll, which comes with Windows

            In order to call these unmanaged functions, the Marshal class is very useful.

            We will also be using the following unusual data types and structures.  Documentation can also be found in
            the MSDN library:

            PSP_DEVICE_INTERFACE_DATA
            PSP_DEVICE_INTERFACE_DETAIL_DATA
            SP_DEVINFO_DATA
            HDEVINFO
            HANDLE
            GUID

            The ultimate objective of the following code is to get the device path, which will be used elsewhere for getting
            read and write handles to the USB device.  Once the read/write handles are opened, only then can this
            PC application begin reading/writing to the USB device using the WriteFile() and ReadFile() functions.

            Getting the device path is a multi-step round about process, which requires calling several of the
            SetupDixxx() functions provided by setupapi.dll.
            */

            try
            {
                IntPtr DeviceInfoTable = IntPtr.Zero;
                SP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA();
                SP_DEVICE_INTERFACE_DETAIL_DATA DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                SP_DEVINFO_DATA DevInfoData = new SP_DEVINFO_DATA();

                uint InterfaceIndex = 0;
                uint dwRegType = 0;
                uint dwRegSize = 0;
                uint dwRegSize2 = 0;
                uint StructureSize = 0;
                IntPtr PropertyValueBuffer = IntPtr.Zero;
                bool MatchFound = false;
                uint ErrorStatus;
                uint LoopCounter = 0;

                //Use the formatting: "Vid_xxxx&Pid_xxxx" where xxxx is a 16-bit hexadecimal number.
                //Make sure the value appearing in the parathesis matches the USB device descriptor
                //of the device that this aplication is intending to find.
                String DeviceIDToFind = "Vid_04d8&Pid_003f";

                //First populate a list of plugged in devices (by specifying "DIGCF_PRESENT"), which are of the specified class GUID.
                DeviceInfoTable = SetupDiGetClassDevs(ref InterfaceClassGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

                if(DeviceInfoTable != IntPtr.Zero)
                {
                    //Now look through the list we just populated.  We are trying to see if any of them match our device.
                    while(true)
                    {
                        InterfaceDataStructure.cbSize = (uint)Marshal.SizeOf(InterfaceDataStructure);
                        if(SetupDiEnumDeviceInterfaces(DeviceInfoTable, IntPtr.Zero, ref InterfaceClassGuid, InterfaceIndex, ref InterfaceDataStructure))
                        {
                            ErrorStatus = (uint)Marshal.GetLastWin32Error();
                            if (ErrorStatus == ERROR_NO_MORE_ITEMS)	//Did we reach the end of the list of matching devices in the DeviceInfoTable?
                            {	//Cound not find the device.  Must not have been attached.
                                SetupDiDestroyDeviceInfoList(DeviceInfoTable);	//Clean up the old structure we no longer need.
                                return false;
                            }
                        }
                        else	//Else some other kind of unknown error ocurred...
                        {
                            ErrorStatus = (uint)Marshal.GetLastWin32Error();
                            SetupDiDestroyDeviceInfoList(DeviceInfoTable);	//Clean up the old structure we no longer need.
                            return false;
                        }

                        //Now retrieve the hardware ID from the registry.  The hardware ID contains the VID and PID, which we will then
                        //check to see if it is the correct device or not.

                        //Initialize an appropriate SP_DEVINFO_DATA structure.  We need this structure for SetupDiGetDeviceRegistryProperty().
                        DevInfoData.cbSize = (uint)Marshal.SizeOf(DevInfoData);
                        SetupDiEnumDeviceInfo(DeviceInfoTable, InterfaceIndex, ref DevInfoData);

                        //First query for the size of the hardware ID, so we can know how big a buffer to allocate for the data.
                        SetupDiGetDeviceRegistryProperty(DeviceInfoTable, ref DevInfoData, SPDRP_HARDWAREID, ref dwRegType, IntPtr.Zero, 0, ref dwRegSize);

                        //Allocate a buffer for the hardware ID.
                        //Should normally work, but could throw exception "OutOfMemoryException" if not enough resources available.
                        PropertyValueBuffer = Marshal.AllocHGlobal((int)dwRegSize);

                        //Retrieve the hardware IDs for the current device we are looking at.  PropertyValueBuffer gets filled with a
                        //REG_MULTI_SZ (array of null terminated strings).  To find a device, we only care about the very first string in the
                        //buffer, which will be the "device ID".  The device ID is a string which contains the VID and PID, in the example
                        //format "Vid_04d8&Pid_003f".
                        SetupDiGetDeviceRegistryProperty(DeviceInfoTable, ref DevInfoData, SPDRP_HARDWAREID, ref dwRegType, PropertyValueBuffer, dwRegSize, ref dwRegSize2);

                        //Now check if the first string in the hardware ID matches the device ID of the USB device we are trying to find.
                        String DeviceIDFromRegistry = Marshal.PtrToStringUni(PropertyValueBuffer); //Make a new string, fill it with the contents from the PropertyValueBuffer

                        Marshal.FreeHGlobal(PropertyValueBuffer);		//No longer need the PropertyValueBuffer, free the memory to prevent potential memory leaks

                        //Convert both strings to lower case.  This makes the code more robust/portable accross OS Versions
                        DeviceIDFromRegistry = DeviceIDFromRegistry.ToLowerInvariant();
                        DeviceIDToFind = DeviceIDToFind.ToLowerInvariant();
                        //Now check if the hardware ID we are looking at contains the correct VID/PID
                        MatchFound = DeviceIDFromRegistry.Contains(DeviceIDToFind);
                        if(MatchFound == true)
                        {
                            //Device must have been found.  In order to open I/O file handle(s), we will need the actual device path first.
                            //We can get the path by calling SetupDiGetDeviceInterfaceDetail(), however, we have to call this function twice:  The first
                            //time to get the size of the required structure/buffer to hold the detailed interface data, then a second time to actually
                            //get the structure (after we have allocated enough memory for the structure.)
                            DetailedInterfaceDataStructure.cbSize = (uint)Marshal.SizeOf(DetailedInterfaceDataStructure);
                            //First call populates "StructureSize" with the correct value
                            SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, ref InterfaceDataStructure, IntPtr.Zero, 0, ref StructureSize, IntPtr.Zero);
                            //Need to call SetupDiGetDeviceInterfaceDetail() again, this time specifying a pointer to a SP_DEVICE_INTERFACE_DETAIL_DATA buffer with the correct size of RAM allocated.
                            //First need to allocate the unmanaged buffer and get a pointer to it.
                            IntPtr pUnmanagedDetailedInterfaceDataStructure = IntPtr.Zero;  //Declare a pointer.
                            pUnmanagedDetailedInterfaceDataStructure = Marshal.AllocHGlobal((int)StructureSize);    //Reserve some unmanaged memory for the structure.
                            DetailedInterfaceDataStructure.cbSize = 6; //Initialize the cbSize parameter (4 bytes for DWORD + 2 bytes for unicode null terminator)
                            Marshal.StructureToPtr(DetailedInterfaceDataStructure, pUnmanagedDetailedInterfaceDataStructure, false); //Copy managed structure contents into the unmanaged memory buffer.

                            //Now call SetupDiGetDeviceInterfaceDetail() a second time to receive the device path in the structure at pUnmanagedDetailedInterfaceDataStructure.
                            if (SetupDiGetDeviceInterfaceDetail(DeviceInfoTable, ref InterfaceDataStructure, pUnmanagedDetailedInterfaceDataStructure, StructureSize, IntPtr.Zero, IntPtr.Zero))
                            {
                                //Need to extract the path information from the unmanaged "structure".  The path starts at (pUnmanagedDetailedInterfaceDataStructure + sizeof(DWORD)).
                                IntPtr pToDevicePath = new IntPtr((uint)pUnmanagedDetailedInterfaceDataStructure.ToInt32() + 4);  //Add 4 to the pointer (to get the pointer to point to the path, instead of the DWORD cbSize parameter)
                                DevicePath = Marshal.PtrToStringUni(pToDevicePath); //Now copy the path information into the globally defined DevicePath String.

                                //We now have the proper device path, and we can finally use the path to open I/O handle(s) to the device.
                                SetupDiDestroyDeviceInfoList(DeviceInfoTable);	//Clean up the old structure we no longer need.
                                Marshal.FreeHGlobal(pUnmanagedDetailedInterfaceDataStructure);  //No longer need this unmanaged SP_DEVICE_INTERFACE_DETAIL_DATA buffer.  We already extracted the path information.
                                return true;    //Returning the device path in the global DevicePath String
                            }
                            else //Some unknown failure occurred
                            {
                                uint ErrorCode = (uint)Marshal.GetLastWin32Error();
                                SetupDiDestroyDeviceInfoList(DeviceInfoTable);	//Clean up the old structure.
                                Marshal.FreeHGlobal(pUnmanagedDetailedInterfaceDataStructure);  //No longer need this unmanaged SP_DEVICE_INTERFACE_DETAIL_DATA buffer.  We already extracted the path information.
                                return false;
                            }
                        }

                        InterfaceIndex++;
                        //Keep looping until we either find a device with matching VID and PID, or until we run out of devices to check.
                        //However, just in case some unexpected error occurs, keep track of the number of loops executed.
                        //If the number of loops exceeds a very large number, exit anyway, to prevent inadvertent infinite looping.
                        LoopCounter++;
                        if(LoopCounter == 10000000)	//Surely there aren't more than 10 million devices attached to any forseeable PC...
                        {
                            return false;
                        }
                    }//end of while(true)
                }
                return false;
            }//end of try
            catch
            {
                //Something went wrong if PC gets here.  Maybe a Marshal.AllocHGlobal() failed due to insufficient resources or something.
                return false;
            }
        }
Example #37
0
        //
        // Return a list of USB Host Controllers
        //
        public static System.Collections.ObjectModel.ReadOnlyCollection<USBController> GetHostControllers()
        {
            List<USBController> HostList = new List<USBController>();
            Guid HostGUID = new Guid(GUID_DEVINTERFACE_HUBCONTROLLER);

            // We start at the "root" of the device tree and look for all
            // devices that match the interface GUID of a Hub Controller
            IntPtr h = SetupDiGetClassDevs(ref HostGUID, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
            if (h.ToInt32() != INVALID_HANDLE_VALUE)
            {
                IntPtr ptrBuf = Marshal.AllocHGlobal(BUFFER_SIZE);
                bool Success;
                int i = 0;
                do
                {
                    USBController host = new USBController();
                    host.ControllerIndex = i;

                    // create a Device Interface Data structure
                    SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA();
                    dia.cbSize = Marshal.SizeOf(dia);

                    // start the enumeration
                    Success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref HostGUID, i, ref dia);
                    if (Success)
                    {
                        // build a DevInfo Data structure
                        SP_DEVINFO_DATA da = new SP_DEVINFO_DATA();
                        da.cbSize = Marshal.SizeOf(da);

                        // build a Device Interface Detail Data structure
                        SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                        if (IntPtr.Size == 8) // for 64 bit operating systems
                            didd.cbSize = 8;
                        else didd.cbSize = 4 + Marshal.SystemDefaultCharSize;

                        // now we can get some more detailed information
                        int nRequiredSize = 0;
                        int nBytes = BUFFER_SIZE;
                        var result = SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nBytes, ref nRequiredSize, ref da);
                        if (result)
                        {
                            host.ControllerDevicePath = didd.DevicePath;

                            // get the Device Description and DriverKeyName
                            int RequiredSize = 0;
                            int RegType = REG_SZ;

                            if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DEVICEDESC, ref RegType, ptrBuf, BUFFER_SIZE, ref RequiredSize))
                            {
                                host.ControllerDeviceDesc = Marshal.PtrToStringAuto(ptrBuf);
                            }
                            if (SetupDiGetDeviceRegistryProperty(h, ref da, SPDRP_DRIVER, ref RegType, ptrBuf, BUFFER_SIZE, ref RequiredSize))
                            {
                                host.ControllerDriverKeyName = Marshal.PtrToStringAuto(ptrBuf);
                            }
                        }
                        HostList.Add(host);
                    }
                    i++;
                } while (Success);

                Marshal.FreeHGlobal(ptrBuf);
                SetupDiDestroyDeviceInfoList(h);
            }

            // convert it into a Collection
            return new System.Collections.ObjectModel.ReadOnlyCollection<USBController>(HostList);
        }
        private bool _obtainDeviceHandle()
        {
            try
            {
                // Used to capture how many bytes are returned by system calls
                UInt32 theBytesReturned = 0;

                // SetupAPI32.DLL Data Structures
                SP_DEVICE_INTERFACE_DETAIL_DATA theDevDetailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                SP_DEVINFO_DATA theDevInfoData = new SP_DEVINFO_DATA();
                theDevInfoData.cbSize = Marshal.SizeOf(theDevInfoData);
                IntPtr theDevInfo = SetupDiGetClassDevs(ref DeviceGuid, IntPtr.Zero, IntPtr.Zero, (int)(DiGetClassFlags.DIGCF_PRESENT | DiGetClassFlags.DIGCF_DEVICEINTERFACE));
                SP_DEVICE_INTERFACE_DATA theInterfaceData = new SP_DEVICE_INTERFACE_DATA();
                theInterfaceData.cbSize = Marshal.SizeOf(theInterfaceData);

                // Check for a Garmin Device
                if (!SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, ref DeviceGuid, 0, ref theInterfaceData) && GetLastError() == ERROR_NO_MORE_ITEMS)
                {
                    gHandle = null;
                    return false;
                }

                // Get the device's file path
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, IntPtr.Zero, 0, ref theBytesReturned, IntPtr.Zero);

                if (theBytesReturned <= 0)
                {
                    gHandle = null;
                    return false;
                }

                IntPtr tmpBuffer = Marshal.AllocHGlobal((int)theBytesReturned);
                if (IntPtr.Size == 4) Marshal.WriteInt32(tmpBuffer, 4 + Marshal.SystemDefaultCharSize);
                else Marshal.WriteInt32(tmpBuffer, 8);

                theDevDetailData.cbSize = Marshal.SizeOf(theDevDetailData);
                SetupDiGetDeviceInterfaceDetail(theDevInfo, ref theInterfaceData, tmpBuffer, theBytesReturned, IntPtr.Zero, ref theDevInfoData);

                IntPtr pDevicePathName = new IntPtr(tmpBuffer.ToInt64() + 4);
                String devicePathName = Marshal.PtrToStringAuto(pDevicePathName);

                // Create a handle to the device
                gHandle = CreateFile(devicePathName, ((UInt32)(GenericAccessRights.GenericRead | GenericAccessRights.GenericWrite)), 0, IntPtr.Zero, (UInt32)FileCreationDisposition.OpenExisting, (UInt32)FileAttributes.Normal, IntPtr.Zero);

                // Get the driver's asynchronous packet size
                if (tmpBuffer.Equals(IntPtr.Zero)) Marshal.FreeHGlobal(tmpBuffer);
                tmpBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(gUSBPacketSize));

                DeviceIoControl(gHandle, IOCTL_USB_PACKET_SIZE, IntPtr.Zero, 0, tmpBuffer, (UInt32)Marshal.SizeOf(gUSBPacketSize), ref theBytesReturned, IntPtr.Zero);

                switch (theBytesReturned)
                {
                    case 2:
                        gUSBPacketSize = Marshal.ReadInt16(tmpBuffer);
                        break;
                    case 4:
                        gUSBPacketSize = Marshal.ReadInt32(tmpBuffer);
                        break;
                    case 8:
                        gUSBPacketSize = Marshal.ReadInt64(tmpBuffer);
                        break;
                }
                if (!tmpBuffer.Equals(IntPtr.Zero)) Marshal.FreeHGlobal(tmpBuffer);
            }
            catch
            {
                return false;
            }

            return true;
        }
Example #39
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(HDEVINFO deviceInfoSet,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
     int deviceInterfaceDetailDataSize, IntPtr requiredSize, IntPtr deviceInfoData);
Example #40
0
    public static InterfaceDetails[] getConnectedDevices()
    {
        InterfaceDetails[] devices = new InterfaceDetails[0];

        //Create structs to hold interface information
        SP_DEVINFO_DATA          devInfo  = new SP_DEVINFO_DATA();
        SP_DEVICE_INTERFACE_DATA devIface = new SP_DEVICE_INTERFACE_DATA();

        devInfo.cbSize  = (uint)Marshal.SizeOf(devInfo);
        devIface.cbSize = (uint)(Marshal.SizeOf(devIface));

        Guid G = new Guid();

        HID.HidD_GetHidGuid(ref G); //Get the guid of the HID device class

        IntPtr i = SetupAPI.SetupDiGetClassDevs(ref G, IntPtr.Zero, IntPtr.Zero, SetupAPI.DIGCF_DEVICEINTERFACE | SetupAPI.DIGCF_PRESENT);

        //Loop through all available entries in the device list, until false
        SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();

        if (IntPtr.Size == 8) // for 64 bit operating systems
        {
            didd.cbSize = 8;
        }
        else
        {
            didd.cbSize = 4 + Marshal.SystemDefaultCharSize;             // for 32 bit systems
        }

        int            j = -1;
        bool           b = true;
        SafeFileHandle tempHandle;

        while (b)
        {
            ++j;
            b = SetupAPI.SetupDiEnumDeviceInterfaces(i, IntPtr.Zero, ref G, (uint)j, ref devIface);
            if (b == false)
            {
                break;
            }

            uint requiredSize = 0;
            SetupAPI.SetupDiGetDeviceInterfaceDetail(i, ref devIface, ref didd, 256, out requiredSize, ref devInfo);
            string devicePath = didd.DevicePath;

            //create file handles using CT_CreateFile
            tempHandle = Kernel32.CreateFile(devicePath, Kernel32.GENERIC_READ | Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_READ | Kernel32.FILE_SHARE_WRITE,
                                             IntPtr.Zero, Kernel32.OPEN_EXISTING, 0, IntPtr.Zero);

            //get capabilites - use getPreParsedData, and getCaps
            //store the reportlengths
            IntPtr ptrToPreParsedData = new IntPtr();
            bool   ppdSucsess         = HID.HidD_GetPreparsedData(tempHandle, ref ptrToPreParsedData);
            if (ppdSucsess == false)
            {
                continue;
            }

            HIDP_CAPS capabilities = new HIDP_CAPS();
            HID.HidP_GetCaps(ptrToPreParsedData, ref capabilities);

            HIDD_ATTRIBUTES attributes = new HIDD_ATTRIBUTES();
            HID.HidD_GetAttributes(tempHandle, ref attributes);

            string productName = "";
            string SN          = "";
            string manfString  = "";
            IntPtr buffer      = Marshal.AllocHGlobal(126);//max alloc for string;
            if (HID.HidD_GetProductString(tempHandle, buffer, 126))
            {
                productName = Marshal.PtrToStringAuto(buffer);
            }
            if (HID.HidD_GetSerialNumberString(tempHandle, buffer, 126))
            {
                SN = Marshal.PtrToStringAuto(buffer);
            }
            if (HID.HidD_GetManufacturerString(tempHandle, buffer, 126))
            {
                manfString = Marshal.PtrToStringAuto(buffer);
            }
            Marshal.FreeHGlobal(buffer);

            //Call freePreParsedData to release some stuff
            HID.HidD_FreePreparsedData(ref ptrToPreParsedData);

            //If connection was sucsessful, record the values in a global struct
            InterfaceDetails productInfo = new InterfaceDetails();
            productInfo.devicePath           = devicePath;
            productInfo.manufacturer         = manfString;
            productInfo.product              = productName;
            productInfo.PID                  = (ushort)attributes.ProductID;
            productInfo.VID                  = (ushort)attributes.VendorID;
            productInfo.versionNumber        = (ushort)attributes.VersionNumber;
            productInfo.IN_reportByteLength  = (int)capabilities.InputReportByteLength;
            productInfo.OUT_reportByteLength = (int)capabilities.OutputReportByteLength;
            productInfo.serialNumber         = SN; //Check that serial number is actually a number

            int newSize = devices.Length + 1;
            Array.Resize(ref devices, newSize);
            devices[newSize - 1] = productInfo;
        }
        SetupAPI.SetupDiDestroyDeviceInfoList(i);

        return(devices);
    }
 /// <summary>
 /// Gets the full string pointed to by <see cref="DevicePath"/>.
 /// </summary>
 /// <param name="pSelf">
 /// Note that this must be the original struct that was initialized by native memory.
 /// It cannot be copied first as interop will not copy any more than the first character.
 /// </param>
 /// <returns>The full string.</returns>
 /// <remarks>
 /// This is a static method rather than an instance method to try to avoid the easy
 /// mistake of calling the method on an instance that was copied.
 /// </remarks>
 public static string GetDevicePath(SP_DEVICE_INTERFACE_DETAIL_DATA* pSelf)
 {
     return Marshal.PtrToStringAuto(new IntPtr(pSelf->DevicePath));
 }
        //----------------------------------------------------------------------
        // returns the device instance handle of a storage volume or 0 on error
        //----------------------------------------------------------------------
        static long GetDrivesDevInstByDeviceNumber(long DeviceNumber, DriveType DriveType, string dosDeviceName)
        {
            bool IsFloppy = dosDeviceName.Contains("\\Floppy");   // who knows a better way?
            Guid guid;

            switch (DriveType)
            {
            case DriveType.DRIVE_REMOVABLE:
                if (IsFloppy)
                {
                    guid = new Guid(GUID_DEVINTERFACE_FLOPPY);
                }
                else
                {
                    guid = new Guid(GUID_DEVINTERFACE_DISK);
                }
                break;

            case DriveType.DRIVE_FIXED:
                guid = new Guid(GUID_DEVINTERFACE_DISK);
                break;

            case DriveType.DRIVE_CDROM:
                guid = new Guid(GUID_DEVINTERFACE_CDROM);
                break;

            default:
                return(0);
            }

            // Get device interface info set handle for all devices attached to system
            IntPtr hDevInfo = SetupDiGetClassDevs(ref guid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

            if (hDevInfo.ToInt32() == INVALID_HANDLE_VALUE)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            // Retrieve a context structure for a device interface of a device information set
            int dwIndex = 0;

            while (true)
            {
                SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA( );
                if (!SetupDiEnumDeviceInterfaces(hDevInfo, null, ref guid, dwIndex, interfaceData))
                {
                    int error = Marshal.GetLastWin32Error( );
                    if (error != ERROR_NO_MORE_ITEMS)
                    {
                        throw new Win32Exception(error);
                    }
                    break;
                }

                SP_DEVINFO_DATA devData = new SP_DEVINFO_DATA( );
                int             size    = 0;
                if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, IntPtr.Zero, 0, ref size, devData))
                {
                    int error = Marshal.GetLastWin32Error( );
                    if (error != ERROR_INSUFFICIENT_BUFFER)
                    {
                        throw new Win32Exception(error);
                    }
                }

                IntPtr buffer = Marshal.AllocHGlobal(size);
                SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA( );
                detailData.cbSize = Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DETAIL_DATA));
                Marshal.StructureToPtr(detailData, buffer, false);

                if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, interfaceData, buffer, size, ref size, devData))
                {
                    Marshal.FreeHGlobal(buffer);
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                IntPtr pDevicePath = ( IntPtr )(( int )buffer + Marshal.SizeOf(typeof(int)));
                string devicePath  = Marshal.PtrToStringAuto(pDevicePath);
                Marshal.FreeHGlobal(buffer);

                // open the disk or cdrom or floppy
                IntPtr hDrive = CreateFile(devicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
                if (hDrive.ToInt32() != INVALID_HANDLE_VALUE)
                {
                    // get its device number
                    long driveDeviceNumber = GetDeviceNumber(hDrive);
                    if (DeviceNumber == driveDeviceNumber)   // match the given device number with the one of the current device
                    {
                        // CloseHandle( hDrive );  // handle hDrive was closed inside GetDeviceNumber(..)
                        SetupDiDestroyDeviceInfoList(hDevInfo);
                        return(devData.devInst);
                    }
                    // CloseHandle( hDrive );  <span style="font-size: 9pt;">// handle hDrive was closed inside GetDeviceNumber(..)</span>
                }
                dwIndex++;
            }

            SetupDiDestroyDeviceInfoList(hDevInfo);
            return(0);
        }
Example #43
0
        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            try
            {
                if (m.Msg == WM_DEVICECHANGE)
                {
                    Thread.Sleep(500);
                    DEV_BROADCAST_HDR pHdr = new DEV_BROADCAST_HDR();
                    pHdr = (DEV_BROADCAST_HDR)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_HDR));
                    switch ((int)m.WParam)
                    {

                        case UsbNotification.DbtDeviceremovecomplete:

                            Console.WriteLine("Usb_DeviceRemoved");
                            break;

                        case UsbNotification.DbtDevicearrival:
                            Console.WriteLine(" Usb_DeviceAdded"); // this is where you do your magic

                            //Console.WriteLine("Hello: {0}", pHdr.dbch_DeviceType);
                            if (pHdr.dbch_DeviceType == 5)
                            {
                                //Console.WriteLine("Human Interface Device");
                                DEV_BROADCAST_DEVICEINTERFACE pDevInf = (DEV_BROADCAST_DEVICEINTERFACE)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_DEVICEINTERFACE));
                                string name = GetDeviceName(pDevInf);
                                //Console.WriteLine("Name: {0}", name);
                                //GetDeviceNameNew(pDevInf);
                                //Console.WriteLine("Size: {0}\nDevice Type: {1}\nreserved: {2}", pDevInf.dbcc_size, pDevInf.dbcc_devicetype, pDevInf.dbcc_reserved);
                                //Console.WriteLine("Details: {0}", pDevInf.dbcc_name);
                                //Console.WriteLine("Class GUID: {0}", pDevInf.dbcc_classguid);
                                string pid = "";
                                string vid = "";
                                getDetails(pDevInf.dbcc_name.ToString(), ref pid, ref vid);
                                Guid DiskGUID = new Guid("A5DCBF10-6530-11D2-901F-00C04FB951ED");
                                IntPtr h = SetupDiGetClassDevs(ref DiskGUID, new IntPtr(0), IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
                                //Console.WriteLine("Class GUID: {0}", DiskGUID);
                                if (h != (IntPtr)INVALID_HANDLE_VALUE)
                                {

                                    bool Success = true;

                                    uint i = 0;
                                    while (Success)
                                    {
                                        // create a Device Interface Data structure
                                        SP_DEVICE_INTERFACE_DATA dia = new SP_DEVICE_INTERFACE_DATA();
                                        dia.cbSize = Marshal.SizeOf(dia);

                                        // start the enumeration
                                        Success = SetupDiEnumDeviceInterfaces(h, IntPtr.Zero, ref DiskGUID, i, ref dia);

                                        if (Success)
                                        {
                                            // build a DevInfo Data structure
                                            //Console.WriteLine("DiskGUID Agian: " + DiskGUID.ToString());
                                            SP_DEVINFO_DATA da = new SP_DEVINFO_DATA();
                                            da.cbSize = 28; // this becomes 32 for 64 bit systems;

                                            // build a Device Interface Detail Data structure
                                            SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
                                            didd.cbSize = 4 + Marshal.SystemDefaultCharSize; // trust me :)

                                            int nRequiredSize = 0;
                                            int nBytes = 256; //Buffer Size = 256
                                            uint n_required_size = (uint)(int)nRequiredSize;
                                            uint nbytes = (uint)(int)nBytes;
                                            if (SetupDiGetDeviceInterfaceDetail(h, ref dia, ref didd, nbytes, out n_required_size, ref da))
                                            {

                                                // Now we get the InstanceID of the USB level device
                                                IntPtr ptrInstanceBuf = Marshal.AllocHGlobal(nBytes);
                                                CM_Get_Device_ID(da.devInst, ptrInstanceBuf, nBytes, 0);
                                                string InstanceID = Marshal.PtrToStringAuto(ptrInstanceBuf);
                                                //Console.WriteLine("Instance ID: " + da.devInst);

                                                //Console.WriteLine("PID: {0}\nVID: {1}", pid, vid);
                                                string pid_temp = "", vid_temp = "";
                                                int storageFlag = 0;
                                                getDetails(InstanceID.ToString(), ref pid_temp, ref vid_temp);

                                                if(pid == pid_temp && vid == vid_temp)
                                                {
                                                    additionalFunctions sa = new additionalFunctions();
                                                    tree.node root = new tree.node(da.devInst);
                                                    //sa.buildTree(root);
                                                    //Console.WriteLine("Device Added: {0} \nGetting Details................{1}....{2}....", InstanceID, pid, vid);
                                                    var test = da.devInst;
                                                    Thread th = new Thread(() =>
                                                    {

                                                        string serialNo = sd.getSerial(InstanceID);
                                                        //Console.WriteLine("Serial Number: {0}", serialNo);
                                                        sd.search(pid, vid, ref storageFlag,     serialNo, test); //Search details of the Given PID VID From WMI
                                                    });
                                                    th.Start();
                                                    th.Join();
                                                    Marshal.FreeHGlobal(ptrInstanceBuf);
                                                    SetupDiDestroyDeviceInfoList(h);
                                                    break;
                                                    /*
                                                    if (storageFlag == 1)
                                                    {
                                                        Console.WriteLine("TRYING TO EJECT!!-------------------" + da.devInst);
                                                        additionalFunctions.checkEject(da.devInst); //Ejects the USB by calling the CM_Request_Device_Eject function
                                                        Console.WriteLine("------------------------------------");
                                                    }
                                                    */
                                                    /*const int BUFFER_SIZE = 256;
                                                    UInt32 RequiredSize;
                                                    UInt32 RegType = 0;
                                                    byte[] ptrBuffer = new byte[BUFFER_SIZE];
                                                    IntPtr test = new IntPtr(BUFFER_SIZE);
                                                    tree.node root1 = new tree.node(da.devInst);
                                                    //additionalFunctions.buildTree(root1);

                                                    if (SetupDiGetDeviceRegistryProperty(h, ref da,(uint) SetupDiGetDeviceRegistryPropertyEnum.SPDRP_DEVICEDESC, out RegType, ptrBuffer, BUFFER_SIZE, out RequiredSize))
                                                    {
                                                        //string ControllerDeviceDesc = Marshal.PtrToStringAuto(ptrBuf);
                                                        //Console.WriteLine("Controller Device Name: {0}", ControllerDeviceDesc);
                                                        SetupDiGetDeviceRegistryProperty(h, ref da, (uint)SetupDiGetDeviceRegistryPropertyEnum.SPDRP_DEVICEDESC, out RegType, ptrBuffer, BUFFER_SIZE, out RequiredSize);
                                                        byte[] data = ptrBuffer;
                                                        IntPtr ptr = Marshal.AllocHGlobal(data.Length);
                                                        try
                                                        {

                                                            //Console.WriteLine("Sibling Status: " + CM_Get_Child(out parentDevInt, da.devInst, 0));
                                                            UInt32 current = da.devInst;
                                                            Microsoft.Win32.RegistryValueKind kind;
                                                            uint length = 0;

                                                            Program.CM_Get_DevNode_Registry_Property(da.devInst, 0x0000001A, out kind, IntPtr.Zero, ref length, 0);
                                                            IntPtr buffer = Marshal.AllocHGlobal((int)length);
                                                            Program.CM_Get_DevNode_Registry_Property(da.devInst, 0x0000001A, out kind, buffer, ref length, 0);
                                                            byte[] test1 = new byte[BUFFER_SIZE];

                                                            Marshal.Copy(buffer,test1, 0, (int)length);

                                                            //Console.WriteLine("dadas" + test1 + "DASdasd" + buffer);
                                                            //Console.WriteLine("\t\tDevice PATH: " + "\t" + System.Text.Encoding.UTF8.GetString(test1).ToString());

                                                            //Console.WriteLine("The New Function------------------\t" + da.devInst);

                                                            //tree.node root = new tree.node(da.devInst);
                                                            //additionalFunctions.buildTree(root);

                                                            String ControllerDesc = System.Text.Encoding.UTF8.GetString(ptrBuffer);
                                                            //Console.WriteLine("Details: {0}", ControllerDesc);
                                                            //Console.WriteLine("Sec Details: {0}", ptrBuffer);

                                                        }
                                                        finally
                                                        {
                                                            Marshal.FreeHGlobal(ptr);
                                                        }

                                                        //Console.WriteLine("Controller: " + RequiredSize);
                                                    }
                                                    else
                                                    {
                                                        if (GetLastError() == 13)
                                                        {
                                                            Console.WriteLine("The Property doesnot exist for the device");
                                                        }
                                                        else
                                                        {
                                                            Console.WriteLine("SetupDiGetDeviceRegistryProperty Error: " + GetLastError().ToString());
                                                        }
                                                    }*/

                                                    //Console.WriteLine("Pid: {0}\nVid:{1}", pid, vid);

                                                }

                                                Marshal.FreeHGlobal(ptrInstanceBuf);

                                            }

                                        }
                                        i++;

                                    }
                                }
                                SetupDiDestroyDeviceInfoList(h);

                            }

                            break;
                    }
                }
                base.WndProc(ref m);

            }
            catch
            {

            }
        }
Example #44
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(HDEVINFO deviceInfoSet,
                                                           ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
                                                           ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
                                                           int deviceInterfaceDetailDataSize, IntPtr requiredSize, IntPtr deviceInfoData);
Example #45
0
        public static interfaceDetails[] getConnectedDevices()
        {
            interfaceDetails[] devices = new interfaceDetails[0];

            //Create structs to hold interface information
            SP_DEVINFO_DATA devInfo = new SP_DEVINFO_DATA();
            SP_DEVICE_INTERFACE_DATA devIface = new SP_DEVICE_INTERFACE_DATA();
            devInfo.cbSize = (uint)Marshal.SizeOf(devInfo);
            devIface.cbSize = (uint)(Marshal.SizeOf(devIface));

            Guid G = new Guid();
            HidD_GetHidGuid(ref G); //Get the guid of the HID device class

            IntPtr i = SetupDiGetClassDevs(ref G, IntPtr.Zero, IntPtr.Zero, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);

            //Loop through all available entries in the device list, until false
            SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            if (IntPtr.Size == 8) // for 64 bit operating systems
                didd.cbSize = 8;
            else
                didd.cbSize = 4 + Marshal.SystemDefaultCharSize; // for 32 bit systems

            int j = -1;
            bool b = true;
            int error;
            SafeFileHandle tempHandle;

            while (b)
            {
                j++;

                b = SetupDiEnumDeviceInterfaces(i, IntPtr.Zero, ref G, (uint)j, ref devIface);
                error = Marshal.GetLastWin32Error();
                if (b == false)
                    break;

                uint requiredSize = 0;
                bool b1 = SetupDiGetDeviceInterfaceDetail(i, ref devIface, ref didd, 256, out requiredSize, ref devInfo);
                string devicePath = didd.DevicePath;

                //create file handles using CT_CreateFile
                tempHandle = CreateFile(devicePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
                    IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                //get capabilites - use getPreParsedData, and getCaps
                //store the reportlengths
                IntPtr ptrToPreParsedData = new IntPtr();
                bool ppdSucsess = HidD_GetPreparsedData(tempHandle, ref ptrToPreParsedData);
                if (ppdSucsess == false)
                    continue;

                HIDP_CAPS capabilities = new HIDP_CAPS();
                int hidCapsSucsess = HidP_GetCaps(ptrToPreParsedData, ref capabilities);

                HIDD_ATTRIBUTES attributes = new HIDD_ATTRIBUTES();
                bool hidAttribSucsess = HidD_GetAttributes(tempHandle, ref attributes);

                string productName = "";
                string SN = "";
                string manfString = "";
                IntPtr buffer = Marshal.AllocHGlobal(126);//max alloc for string;
                if (HidD_GetProductString(tempHandle, buffer, 126)) productName = Marshal.PtrToStringAuto(buffer);
                if (HidD_GetSerialNumberString(tempHandle, buffer, 126)) SN = Marshal.PtrToStringAuto(buffer);
                if (HidD_GetManufacturerString(tempHandle, buffer, 126)) manfString = Marshal.PtrToStringAuto(buffer);
                Marshal.FreeHGlobal(buffer);

                //Call freePreParsedData to release some stuff
                HidD_FreePreparsedData(ref ptrToPreParsedData);

                //If connection was sucsessful, record the values in a global struct
                interfaceDetails productInfo = new interfaceDetails();
                productInfo.devicePath = devicePath;
                productInfo.manufacturer = manfString;
                productInfo.product = productName;
                productInfo.PID = (ushort)attributes.ProductID;
                productInfo.VID = (ushort)attributes.VendorID;
                productInfo.versionNumber = (ushort)attributes.VersionNumber;
                productInfo.IN_reportByteLength = (int)capabilities.InputReportByteLength;
                productInfo.OUT_reportByteLength = (int)capabilities.OutputReportByteLength;

                if (stringIsInteger(SN))
                    productInfo.serialNumber = Convert.ToInt32(SN);     //Check that serial number is actually a number

                int newSize = devices.Length + 1;
                Array.Resize(ref devices, newSize);
                devices[newSize - 1] = productInfo;
            }
            SetupDiDestroyDeviceInfoList(i);

            return devices;
        }
Example #46
0
        public static List<string> GetAllDevices(int? vendorId, int? productId)
        {
            int index = 0;
              GUID guid = new GUID();
              var ret = new List<string>();

              HidD_GetHidGuid(ref guid);
              IntPtr devicesHandle = SetupDiGetClassDevs(ref guid, null, IntPtr.Zero, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT);
              var diData = new SP_DEVICE_INTERFACE_DATA();
              diData.cbSize = Marshal.SizeOf(diData);

              while (SetupDiEnumDeviceInterfaces(devicesHandle, IntPtr.Zero, ref guid, index, ref diData))
              {
            //Get the buffer size
            UInt32 size;
            SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

            // Uh...yeah.
            var diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

            //Get detailed information
            if (SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, ref diDetail, size, out size, IntPtr.Zero))
            {
              //Get a handle to this device
              var handle = CreateFile(diDetail.DevicePath, FileAccess.ReadWrite, FileShare.ReadWrite,
            IntPtr.Zero, FileMode.Open, EFileAttributes.Overlapped, IntPtr.Zero);

              //Get this device's attributes
              var attrib = new HIDD_ATTRIBUTES();
              attrib.Size = Marshal.SizeOf(attrib);
              if (HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
              {
            //See if this is one we care about
            if ((!vendorId.HasValue || ((attrib.VendorID & 0xFFFF) == vendorId.Value)) &&
              (!productId.HasValue || ((attrib.ProductID & 0xFFFF) == productId.Value)))
            {
              ret.Add(diDetail.DevicePath);
              break;
            }
              }

              //Close the handle
              handle.Close();
            }

            //Move on
            index++;
              }

              SetupDiDestroyDeviceInfoList(devicesHandle);

              return ret;
        }
    /// <summary>
    /// Get Device data for the given device number
    /// </summary>
    /// <param name="DeviceNumber">Device number</param>
    /// <returns>Deice data</returns>
    private static SP_DEVINFO_DATA GetDevInfoForDeviceNumber(long DeviceNumber)
    {
      SP_DEVINFO_DATA result = null;
      Guid guid = new Guid(GUID_DEVINTERFACE_DISK);

      IntPtr _deviceInfoSet = SetupDiGetClassDevs(ref guid, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

      if (_deviceInfoSet.ToInt32() == INVALID_HANDLE_VALUE)
      {
        return result;
      }
      int index = 0;
      while (true)
      {
        SP_DEVICE_INTERFACE_DATA interfaceData = new SP_DEVICE_INTERFACE_DATA();

        if (!SetupDiEnumDeviceInterfaces(_deviceInfoSet, null, ref guid, index, interfaceData))
        {
          int error = Marshal.GetLastWin32Error();
          if (error != ERROR_NO_MORE_ITEMS)
            throw new Win32Exception(error);
          break;
        }

        SP_DEVINFO_DATA devData = new SP_DEVINFO_DATA();
        int size = 0;
        if (!SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, interfaceData, IntPtr.Zero, 0, ref size, devData))
        {
          int error = Marshal.GetLastWin32Error();
          if (error != ERROR_INSUFFICIENT_BUFFER)
            throw new Win32Exception(error);
        }

        IntPtr buffer = Marshal.AllocHGlobal(size);
        SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
        detailData.cbSize = Marshal.SizeOf(typeof (SP_DEVICE_INTERFACE_DETAIL_DATA));
        Marshal.StructureToPtr(detailData, buffer, false);

        if (!SetupDiGetDeviceInterfaceDetail(_deviceInfoSet, interfaceData, buffer, size, ref size, devData))
        {
          Marshal.FreeHGlobal(buffer);
          throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        IntPtr pDevicePath = (IntPtr)((int)buffer + Marshal.SizeOf(typeof (int)));
        string devicePath = Marshal.PtrToStringAuto(pDevicePath);
        Marshal.FreeHGlobal(buffer);
        if (GetDeviceNumber(devicePath) == DeviceNumber)
        {
          result = devData;
          break;
        }

        index++;
      }

      return result;
    }
 public static extern Boolean SetupDiGetDeviceInterfaceDetail(
                                                                 IntPtr hDevInfo,
                                                                 ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
                                                                 ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
                                                                 uint deviceInterfaceDetailDataSize,
                                                                 ref uint requiredSize,//out UInt32 requiredSize,
                                                                 IntPtr deviceInfoData//ref SP_DEVINFO_DATA deviceInfoData
                                                                 );
Example #49
0
 public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA oDetailData, int nDeviceInterfaceDetailDataSize, out int nRequiredSize, IntPtr lpDeviceInfoData);
        public string GetDevicePath()
        {
            Guid deviceGuid = new Guid("573E8C73-0CB4-4471-A1BF-FAB26C31D384");
            IntPtr DeviceInfo = SetupDiGetClassDevs(ref deviceGuid, IntPtr.Zero, IntPtr.Zero, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
            if (DeviceInfo == (IntPtr)(-1))
            {
                Console.WriteLine("SetupDiGetClassDevs Failed");
                return "";
            }

            SP_DEVICE_INTERFACE_DATA deviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
            deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);

            bool result = SetupDiEnumDeviceInterfaces(DeviceInfo, IntPtr.Zero, ref deviceGuid, 0, ref deviceInterfaceData);

            if (!result)
            {
                Console.WriteLine("SetupDiEnumDeviceInterfaces Failed");
                SetupDiDestroyDeviceInfoList(DeviceInfo);
                return "";
            }

            uint requiredSize = 0;

            SetupDiGetDeviceInterfaceDetail(DeviceInfo, ref deviceInterfaceData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
            SP_DEVICE_INTERFACE_DETAIL_DATA didd = new SP_DEVICE_INTERFACE_DETAIL_DATA();
            if (requiredSize < Marshal.SizeOf(didd))
            {
                didd.cbSize = 8;  //Test for 64bit
                uint length = requiredSize;
                result = SetupDiGetDeviceInterfaceDetail(DeviceInfo, ref deviceInterfaceData, ref didd, length, out requiredSize, IntPtr.Zero);
            }

            Console.WriteLine("NameLength = " + didd.DevicePath.Length);
            Console.WriteLine("Name = " + didd.DevicePath);

            SetupDiDestroyDeviceInfoList(DeviceInfo);
            if (!result)
                return "\\\\?\\usb#vid_1603&pid_0002&mi_01#6&b8aa88a&0&0001#{573e8c73-0cb4-4471-a1bf-fab26c31d384}";

            return didd.DevicePath;
        }
 public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr hDeviceInfoSet, 
     ref SP_DEVICE_INTERFACE_DATA        DeviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData,
     int DeviceInterfaceDetailDataSize,
     out int cbRequired,
     IntPtr DeviceInfoData);
 private static extern Boolean SetupDiGetDeviceInterfaceDetail(
     IntPtr hDevInfo,
     ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData,
     ref SP_DEVICE_INTERFACE_DETAIL_DATA deviceInterfaceDetailData,
     Int32 deviceInterfaceDetailDataSize,
     IntPtr requiredSize,                                        // null
     [MarshalAs(UnmanagedType.AsAny)] object deviceInfoData      // null
     );
        //--------------------------------------------------------------------------
        // 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);
                    }
                }
            }
Example #54
0
		private void _Init(string devicePath, bool throwNotFoundError)
		{
			bool result;
			int deviceCount = 0;
			uint size;
			uint requiredSize;

			_guid = new Guid();
			HidD_GetHidGuid(ref _guid);

			_hDeviceInfo = SetupDiGetClassDevs(ref _guid, IntPtr.Zero, IntPtr.Zero, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT);

			do
			{
				_SP_DEVICE_INTERFACE_DATA = new SP_DEVICE_INTERFACE_DATA();
				_SP_DEVICE_INTERFACE_DATA.cbSize = Marshal.SizeOf(_SP_DEVICE_INTERFACE_DATA);
				result = SetupDiEnumDeviceInterfaces(_hDeviceInfo, IntPtr.Zero, ref _guid, deviceCount, ref _SP_DEVICE_INTERFACE_DATA);
				SetupDiGetDeviceInterfaceDetail(_hDeviceInfo, ref _SP_DEVICE_INTERFACE_DATA, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
				size = requiredSize;
				var diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
				diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);
				SetupDiGetDeviceInterfaceDetail(_hDeviceInfo, ref _SP_DEVICE_INTERFACE_DATA, ref diDetail,
					size, out requiredSize, IntPtr.Zero);
				_devicePath = diDetail.DevicePath;

				if (_devicePath == devicePath)
				{
					_found = true;
					_SP_DEVICE_INTERFACE_DATA = new SP_DEVICE_INTERFACE_DATA();
					_SP_DEVICE_INTERFACE_DATA.cbSize = Marshal.SizeOf(_SP_DEVICE_INTERFACE_DATA);
					SetupDiEnumDeviceInterfaces(_hDeviceInfo, IntPtr.Zero, ref _guid, deviceCount, ref _SP_DEVICE_INTERFACE_DATA);
					size = 0;
					requiredSize = 0;
					SetupDiGetDeviceInterfaceDetail(_hDeviceInfo, ref _SP_DEVICE_INTERFACE_DATA, IntPtr.Zero, size, out requiredSize, IntPtr.Zero);
					SetupDiGetDeviceInterfaceDetail(_hDeviceInfo, ref _SP_DEVICE_INTERFACE_DATA, IntPtr.Zero, size, out requiredSize, IntPtr.Zero);
					_hidHandle = CreateFile(_devicePath, (uint)FileAccess.ReadWrite, (uint)FileShare.ReadWrite, IntPtr.Zero, (uint)FileMode.Open, (uint)EFileAttributes.Overlapped, IntPtr.Zero);

					//Get report lengths
					IntPtr preparsedDataPtr = (IntPtr)0xffffffff;
					if (HidD_GetPreparsedData(_hidHandle, ref preparsedDataPtr) != 0)
					{
						var caps = new HIDP_CAPS();
						HidP_GetCaps(preparsedDataPtr, ref caps);
						OutputReportLength = caps.OutputReportByteLength;
						InputReportLength = caps.InputReportByteLength;

						_stream = new FileStream(_hidHandle, FileAccess.ReadWrite, InputReportLength, true);
						var buffer = new byte[InputReportLength];
						_stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadData), buffer);
					}

					break;
				}

				deviceCount++;
			} while (result);

			if (!_found)
			{
				if (throwNotFoundError)
					throw new InvalidOperationException("Device not found");
			}
		}
Example #55
0
		public static List<HIDDeviceEntry> GetAllDevices(Guid guid, int? vendorId = null, int? productId = null)
		{
			int index = 0;
			//GUID guid = new GUID();
			var devices = new List<HIDDeviceEntry>();

			if (guid == Guid.Empty)
			{
				HidD_GetHidGuid(ref guid);
			}
			IntPtr devicesHandle = SetupDiGetClassDevs(ref guid, IntPtr.Zero, IntPtr.Zero, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT);
			var diData = new SP_DEVICE_INTERFACE_DATA();
			diData.cbSize = Marshal.SizeOf(diData);

			while (SetupDiEnumDeviceInterfaces(devicesHandle, IntPtr.Zero, ref guid, index, ref diData))
			{
				//Get the buffer size
				UInt32 size;
				SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, IntPtr.Zero, 0, out size, IntPtr.Zero);

				// Uh...yeah.
				var diDetail = new SP_DEVICE_INTERFACE_DETAIL_DATA();
				diDetail.cbSize = (uint)(IntPtr.Size == 8 ? 8 : 5);

				//Get detailed information
				if (SetupDiGetDeviceInterfaceDetail(devicesHandle, ref diData, ref diDetail, size, out size, IntPtr.Zero))
				{
					//Get a handle to this device
					var handle = CreateFile(diDetail.DevicePath, 4 /*GENERIC_WRITE*/, 3 /*FILE_SHARE_READ | FILE_SHARE_WRITE*/, IntPtr.Zero, 4 /*OPEN_EXISTING*/, 0, IntPtr.Zero);
					if (handle.IsInvalid == false)
					{
						//Get this device's attributes
						var attrib = new HIDD_ATTRIBUTES();
						attrib.Size = Marshal.SizeOf(attrib);
						if (HidD_GetAttributes(handle.DangerousGetHandle(), ref attrib))
						{
							int vid = attrib.VendorID & 0xFFFF;
							int pid = attrib.ProductID & 0xFFFF;
							//See if this is one we care about
							if ((!vendorId.HasValue || vid == vendorId.Value) &&
								(!productId.HasValue || pid == productId.Value))
							{
								devices.Add(new HIDDeviceEntry(diDetail.DevicePath, vid, pid));
								break;
							}
						}
					}

					//Close the handle
					handle.Close();
					//CloseHandle(handle);
				}

				//Move on
				index++;
			}

			SetupDiDestroyDeviceInfoList(devicesHandle);

			return devices;
		}