Пример #1
0
        private static string GetDeviceName(DEV_BROADCAST_DEVICEINTERFACE dvi)
        {
            var parts = dvi.dbcc_name.Split('#');
            if (parts.Length <= 3) return "(Unkown device): " + dvi.dbcc_name;
            var type = parts[0].Substring(parts[0].IndexOf(@"?\", StringComparison.Ordinal) + 2);
            var iid = parts[1];
            var uid = parts[2];

            var regPath = string.Format(@"SYSTEM\CurrentControlSet\Enum\{0}\{1}\{2}", type, iid, uid);
            using (var key = Registry.LocalMachine.OpenSubKey(regPath))
            {
                if (key == null) return "(Unkown device): " + dvi.dbcc_name;
                var friendlyName = key.GetValue("FriendlyName");
                var devDesc = key.GetValue("DeviceDesc");

                if (friendlyName != null) return friendlyName.ToString().Split(';').Last();
                if (devDesc != null) return devDesc.ToString().Split(';').Last();
            }

            return "(Unkown device): " + dvi.dbcc_name;
        }
Пример #2
0
        private void RegisterForNotifications()
        {
            var filter = new DEV_BROADCAST_DEVICEINTERFACE
            {
                dbcc_size = Marshal.SizeOf(typeof(DEV_BROADCAST_DEVICEINTERFACE)),
                dbcc_devicetype = DeviceTypes.DBT_DEVTYP_DEVICEINTERFACE,
                // dbcc_classguid = new Guid(0x25dbce51, 0x6c8f, 0x4a72, 0x8a,0x6d,0xb5,0x4c,0x2b,0x4f,0xc8,0x35)
            };

            var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(filter));

            try
            {
                Marshal.StructureToPtr(filter, ptr, false);
                var result = User32.RegisterDeviceNotification(this.Handle, ptr, (int)User32.Flags.DEVICE_NOTIFY_ALL_INTERFACE_CLASSES);
                if (result == IntPtr.Zero)
                {
                    throw new Exception("Could not register for device notifications: " + GetLastFormattedError());
                }
                _notificationHandle = result;
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }