Exemplo n.º 1
0
        /// <summary>
        /// Attempts to get a USB configuration descriptor based on its index.
        /// </summary>
        /// <param name="configIndex">
        /// The index of the configuration you wish to retrieve
        /// </param>
        /// <param name="descriptor">
        /// The requested descriptor.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if the descriptor could be loaded correctly; otherwise,
        /// <see langword="false" ">.
        /// </returns>
        public unsafe bool TryGetConfigDescriptor(byte configIndex, out UsbConfigInfo descriptor)
        {
            this.EnsureNotDisposed();

            ConfigDescriptor *list  = null;
            UsbConfigInfo     value = null;

            try
            {
                var ret = NativeMethods.GetConfigDescriptor(this.device, configIndex, &list);

                if (ret == Error.NotFound)
                {
                    descriptor = null;
                    return(false);
                }

                ret.ThrowOnError();

                value      = UsbConfigInfo.FromUsbConfigDescriptor(this, list[0]);
                descriptor = value;
                return(true);
            }
            finally
            {
                if (list != null)
                {
                    NativeMethods.FreeConfigDescriptor(list);
                }
            }
        }
Exemplo n.º 2
0
        private void DealCallbackInThread(Tuple <int, IntPtr> arg)
        {
            int    state     = arg.Item1;
            IntPtr devicePtr = arg.Item2;

            if (state == 1)     //设备连接
            {
                var devInfo = (UsbDeviceInfo)Marshal.PtrToStructure(devicePtr, typeof(UsbDeviceInfo));

                OnUsbDeviceStateChanged?.Invoke(true, devInfo);
                OnUsbDeviceConnected?.Invoke();
                LoggerManagerSingle.Instance.Info($"设备连接:vid={devInfo.VID:X}, pid={devInfo.PID:X}, isPhone={devInfo.IsPhone}, desc={devInfo.GetDeviceDesc()}, type={devInfo.GetDeviceType()}");
            }
            else   //设备断开
            {
                var           devInfoStr = Marshal.PtrToStringAnsi(devicePtr);
                var           infoStr    = devInfoStr.Split('#');
                UsbDeviceInfo devInfo    = new UsbDeviceInfo();
                if (infoStr.Length > 2)
                {
                    string[] vpID;
                    if (GetVIDPID(infoStr[1], out vpID))
                    {
                        devInfo.VID = Convert.ToUInt32(vpID[0], 16);
                        devInfo.PID = Convert.ToUInt32(vpID[1], 16);
                    }

                    OnUsbDeviceStateChanged?.Invoke(false, devInfo);
                    OnUsbDeviceDisConnected?.Invoke();
                    LoggerManagerSingle.Instance.Info($"断开设备:vid={devInfo.VID:X}, pid={devInfo.PID:X}, str={devInfoStr}");
                }
            }
        }
Exemplo n.º 3
0
 private void SetFieldsText(UsbDeviceInfo udf)
 {
     txtPID.Text    = udf != null ? udf.PID : string.Empty;
     txtVID.Text    = udf != null ? udf.VID : string.Empty;
     txtSize.Text   = udf?.Size.ToString() ?? string.Empty;
     txtSerial.Text = udf != null ? udf.SerialNumber : string.Empty;
 }
Exemplo n.º 4
0
        static InjectService()
        {
            if (HACGUIKeyset.TempLockpickPayloadFileInfo.Exists)
            {
                HACGUIKeyset.TempLockpickPayloadFileInfo.Delete();
            }


            // Create event handlers to detect when a device is added or removed
            CreateWatcher = new ManagementEventWatcher();
            WqlEventQuery createQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'");

            CreateWatcher.EventArrived += new EventArrivedEventHandler((s, e) =>
            {
                Refresh();
                if (WMIDeviceInfo != null)
                {
                    DeviceInserted?.Invoke();
                }
            });
            CreateWatcher.Query = createQuery;

            DeleteWatcher = new ManagementEventWatcher();
            WqlEventQuery deleteQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'");

            DeleteWatcher.EventArrived += new EventArrivedEventHandler((s, e) =>
            {
                WMIDeviceInfo = null;
                Refresh();
                if (WMIDeviceInfo == null)
                {
                    DeviceRemoved?.Invoke();
                }
            });
            DeleteWatcher.Query = deleteQuery;

            DeviceInserted += () =>
            {
                StatusService.RCMStatus = StatusService.Status.OK;
                if (!LibusbKInstalled)
                {
                    MessageBoxResult result = MessageBox.Show("You have plugged in your console, but it lacks the libusbK driver. Want to install it? (You cannot inject anything until this is done)", "", MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.Yes)
                    {
                        InstallDriver();
                    }
                }
            };

            DeviceRemoved += () =>
            {
                StatusService.RCMStatus = StatusService.Status.Incorrect;
            };
        }
        /// <summary>
        /// Is the RFID reader writer connected?
        /// </summary>
        /// <returns></returns>
        private bool IsRFIDReaderConnected()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;

            foreach (UsbRegistry usbRegistry in allDevices)
            {
                UsbDeviceInfo deviceInfo = usbRegistry.Device.Info;
                return(IsThisRFIDReader(deviceInfo.Descriptor.VendorID, deviceInfo.Descriptor.ProductID));
            }

            return(false);
        }
Exemplo n.º 6
0
        public WinUsbDevice(String path, WinUsbRegistry registry)
        {
            this.Registry = registry;
            DeviceHandle  = Kernel32.CreateFile(path,
                                                NativeFileAccess.FILE_GENERIC_WRITE | NativeFileAccess.FILE_GENERIC_READ,
                                                NativeFileShare.FILE_SHARE_WRITE | NativeFileShare.FILE_SHARE_READ,
                                                IntPtr.Zero,
                                                NativeFileMode.OPEN_EXISTING,
                                                NativeFileFlag.FILE_ATTRIBUTE_NORMAL | NativeFileFlag.FILE_FLAG_OVERLAPPED,
                                                IntPtr.Zero);
            if (DeviceHandle.IsInvalid || DeviceHandle.IsClosed)
            {
                throw new Win32Exception();
            }
            ThreadPool.BindHandle(DeviceHandle);
            SafeWinUsbInterfaceHandle InterfaceHandle;

            if (!WinUsb_Initialize(DeviceHandle, out InterfaceHandle))
            {
                throw new Win32Exception();
            }
            if (InterfaceHandle.IsInvalid || InterfaceHandle.IsClosed)
            {
                throw new Win32Exception();
            }
            InterfaceHandles = new SafeWinUsbInterfaceHandle[1] {
                InterfaceHandle
            };
            foreach (UsbInterfaceInfo ifinfo in UsbDeviceInfo.FromDevice(this).FindConfiguration(Configuration).Interfaces)
            {
                foreach (UsbEndpointDescriptor epinfo in ifinfo.Endpoints)
                {
                    int epidx = epinfo.EndpointAddress & 0x7F;
                    if ((epinfo.EndpointAddress & 0x80) != 0)
                    {
                        if (EndpointToInterfaceIn.Length <= epidx)
                        {
                            Array.Resize(ref EndpointToInterfaceIn, epidx + 1);
                        }
                        EndpointToInterfaceIn[epidx] = ifinfo.Descriptor.InterfaceNumber;
                    }
                    else
                    {
                        if (EndpointToInterfaceOut.Length <= epidx)
                        {
                            Array.Resize(ref EndpointToInterfaceOut, epidx + 1);
                        }
                        EndpointToInterfaceOut[epidx] = ifinfo.Descriptor.InterfaceNumber;
                    }
                }
            }
        }
        private void Device_Removed(object sender, EventArrivedEventArgs e)
        {
            var instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];

            var deviceInfo = new UsbDeviceInfo(
                instance.GetPropertyValue("DeviceID").ToStringOrEmpty(),
                instance.GetPropertyValue("PNPDeviceID").ToStringOrEmpty(),
                instance.GetPropertyValue("Description").ToStringOrEmpty()
                );

            if (this.OnDeviceRemoved != null && this.EnableRaisingEvents)
            {
                this.OnDeviceRemoved(this, new EventArgs <UsbDeviceInfo>(deviceInfo));
            }
        }
Exemplo n.º 8
0
        public static void Refresh()
        {
            WMIDeviceInfo = null;
            Device        = null;
            DeviceWrapper = null;
            foreach (UsbDeviceInfo info in CreateUsbControllerDeviceInfos(GetUsbDevices()))
            {
                if (info.DeviceID.StartsWith($"USB\\VID_{VID}&PID_{PID}"))
                {
                    WMIDeviceInfo = info;
                    var patternMatch = new KLST_PATTERN_MATCH {
                        ClassGUID = WMIDeviceInfo.ClassGuid
                    };
                    var deviceList = new LstK(0, ref patternMatch);
                    deviceList.MoveNext(out KLST_DEVINFO_HANDLE deviceInfo);

                    Device = new UsbK(deviceInfo);
                    Device.SetAltInterface(0, false, 0);
                    DeviceWrapper = new UsbKWrapper(Device);
                    break;
                }
            }
        }
Exemplo n.º 9
0
        public static void Scan()
        {
            WMIDeviceInfo = null;
            Device        = null;
            DeviceWrapper = null;
            foreach (UsbDeviceInfo info in AllUsbDevices)
            {
                if (info.DeviceID.StartsWith($"USB\\VID_{VID}&PID_{PID}"))
                {
                    WMIDeviceInfo = info;

                    if (!LibusbKInstalled)
                    {
                        MessageBoxResult result = MessageBox.Show("You have plugged in your console, but it lacks the libusbK driver. Want to install it? (You cannot inject anything until this is done)", "", MessageBoxButton.YesNo);
                        if (result == MessageBoxResult.Yes)
                        {
                            InstallDriver();
                        }
                        WMIDeviceInfo = AllUsbDevices.First(x => x.DeviceID == WMIDeviceInfo.DeviceID); // we need to refresh the info
                    }

                    if (LibusbKInstalled)
                    {
                        var patternMatch = new KLST_PATTERN_MATCH {
                            ClassGUID = WMIDeviceInfo.ClassGuid
                        };
                        var deviceList = new LstK(0, ref patternMatch);
                        deviceList.MoveNext(out KLST_DEVINFO_HANDLE deviceInfo);

                        Device = new UsbK(deviceInfo);
                        Device.SetAltInterface(0, false, 0);
                        DeviceWrapper = new UsbKWrapper(Device);
                    }
                    break;
                }
            }
        }
Exemplo n.º 10
0
        static InjectService()
        {
            // Create event handlers to detect when a device is added or removed
            CreateWatcher = new ManagementEventWatcher();
            WqlEventQuery createQuery = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'");

            CreateWatcher.EventArrived += new EventArrivedEventHandler((s, e) =>
            {
                Refresh();
            });
            CreateWatcher.Query = createQuery;

            DeleteWatcher = new ManagementEventWatcher();
            WqlEventQuery deleteQuery = new WqlEventQuery("SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_PnPEntity'");

            DeleteWatcher.EventArrived += new EventArrivedEventHandler((s, e) =>
            {
                WMIDeviceInfo = null;
                Refresh();
                if (WMIDeviceInfo == null)
                {
                    DeviceRemoved?.Invoke();
                }
            });
            DeleteWatcher.Query = deleteQuery;

            DeviceInserted += () =>
            {
                StatusService.RCMStatus = StatusService.Status.OK;
            };

            DeviceRemoved += () =>
            {
                StatusService.RCMStatus = StatusService.Status.Incorrect;
            };
        }
Exemplo n.º 11
0
        public MainForm()
        {
            InitializeComponent();
            var           dw  = new DeviceWatcher(System.Threading.SynchronizationContext.Current);
            UsbDeviceInfo udf = null;

            ejectButton.Enabled = !string.IsNullOrEmpty(txtPID.Text);
            ejectButton.Click  += (sender, args) =>
            {
                if (udf == null)
                {
                    return;
                }
                var ejectionResult = WinAPI.EjectDrive(udf.VolumeLabel);
                //udf = null;
                //dw.Restart();
            };
            dw.DeviceInserted += (o) =>
            {
                udf = new UsbDeviceInfo()
                {
                    PnpDeviceID = o.GetPropertyValue("PNPDeviceID").ToString()
                };
            };

            dw.DeviceRemoved += (o) =>
            {
                if (udf == null || udf.PnpDeviceID != o.GetPropertyValue("PNPDeviceID").ToString())
                {
                    return;
                }
                udf = null;
                SetFieldsText(udf);
            };

            dw.DiskDriveInserted += (o) =>
            {
                //Ждём пока выстрелит событие DeviceInserted
                while (udf == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                udf.Size         = (ulong)o.GetPropertyValue("Size");
                udf.SerialNumber = o.GetPropertyValue("SerialNumber").ToString();
                SetFieldsText(udf);
            };

            dw.VolumeMounted += (o) =>
            {
                //Ждём пока выстрелит событие DeviceInserted
                while (udf == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                udf.VolumeDeviceID = o.GetPropertyValue("DeviceID").ToString();
                udf.VolumeLabel    = o.GetPropertyValue("Caption").ToString().Substring(0, 2);
            };

            dw.VolumeDismounted += (o) =>
            {
                if (udf == null || udf.VolumeDeviceID != o.GetPropertyValue("DeviceID").ToString())
                {
                    return;
                }
                udf = null;
                SetFieldsText(udf);
            };
            dw.PartitionArrived += (o) =>
            {
                //Ждём пока выстрелит событие DeviceInserted
                while (udf == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                udf.PartitionDeviceID = o.GetPropertyValue("DeviceID").ToString();
            };

            dw.PartitionRemoved += (o) =>
            {
                if (udf == null || udf.PartitionDeviceID != o.GetPropertyValue("DeviceID").ToString())
                {
                    return;
                }
                udf = null;
                SetFieldsText(udf);
            };
            //Остановка событий при закрытии формы
            FormClosing += (s, e) => { dw.Stop(); };
        }
Exemplo n.º 12
0
 public UsbDeviceInfo(UsbDeviceInfo usbDeviceInfo)
 {
     this.DeviceId    = usbDeviceInfo.DeviceId;
     this.Description = usbDeviceInfo.Description;
 }
Exemplo n.º 13
0
 public UsbDeviceInfoModel(UsbDeviceInfo usbDeviceInfo, UsbDeviceState state) : base(usbDeviceInfo)
 {
     this.State = state;
 }
 public UsbDeviceArrivedEventArgs(char driveLetter, UsbDeviceInfo deviceInfo)
 {
     this.DriveLetter   = driveLetter;
     this.USBDeviceInfo = deviceInfo;
 }