RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 891397
Accepted
Vipz
Vipz
Asked:2020-10-10 22:38:31 +0000 UTC2020-10-10 22:38:31 +0000 UTC 2020-10-10 22:38:31 +0000 UTC

启用/禁用 USB 端口或设备

  • 772

操作系统 - Windows 10 x64

如何以编程方式禁用/阻止 USB 端口(以便此时设备处于非活动状态)?

起初我想关闭一个特定的设备,我尝试了从 cenSO和翻译到的几个选项ruSO,但一切都建立在无法关闭某些设备的事实上。

在此处输入图像描述

我认为您可以关闭 USB 端口。

我enSO发现一次禁用所有端口,并且此方法仅在重新启动后才有效。

是否可以在不重新启动的情况下关闭电源/阻止特定的 USB 端口?或者禁用非禁用设备?

c#
  • 2 2 个回答
  • 10 Views

2 个回答

  • Voted
  1. Best Answer
    Andrew_STOP_RU_AGRESSION_IN_UA
    2020-11-03T23:08:18Z2020-11-03T23:08:18Z

    在网上找到了这门课:

    using System;
    using System.Text;
    using System.Collections.Generic;
    using DisableDevice;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using Microsoft.Win32.SafeHandles;
    using System.Security;
    using System.Runtime.ConstrainedExecution;
    using System.Management;
    
    namespace DisableDevice
    {
    
        [Flags()]
        internal enum SetupDiGetClassDevsFlags
        {
            Default = 1,
            Present = 2,
            AllClasses = 4,
            Profile = 8,
            DeviceInterface = (int)0x10
        }
    
        internal enum DiFunction
        {
            SelectDevice = 1,
            InstallDevice = 2,
            AssignResources = 3,
            Properties = 4,
            Remove = 5,
            FirstTimeSetup = 6,
            FoundDevice = 7,
            SelectClassDrivers = 8,
            ValidateClassDrivers = 9,
            InstallClassDrivers = (int)0xa,
            CalcDiskSpace = (int)0xb,
            DestroyPrivateData = (int)0xc,
            ValidateDriver = (int)0xd,
            Detect = (int)0xf,
            InstallWizard = (int)0x10,
            DestroyWizardData = (int)0x11,
            PropertyChange = (int)0x12,
            EnableClass = (int)0x13,
            DetectVerify = (int)0x14,
            InstallDeviceFiles = (int)0x15,
            UnRemove = (int)0x16,
            SelectBestCompatDrv = (int)0x17,
            AllowInstall = (int)0x18,
            RegisterDevice = (int)0x19,
            NewDeviceWizardPreSelect = (int)0x1a,
            NewDeviceWizardSelect = (int)0x1b,
            NewDeviceWizardPreAnalyze = (int)0x1c,
            NewDeviceWizardPostAnalyze = (int)0x1d,
            NewDeviceWizardFinishInstall = (int)0x1e,
            Unused1 = (int)0x1f,
            InstallInterfaces = (int)0x20,
            DetectCancel = (int)0x21,
            RegisterCoInstallers = (int)0x22,
            AddPropertyPageAdvanced = (int)0x23,
            AddPropertyPageBasic = (int)0x24,
            Reserved1 = (int)0x25,
            Troubleshooter = (int)0x26,
            PowerMessageWake = (int)0x27,
            AddRemotePropertyPageAdvanced = (int)0x28,
            UpdateDriverUI = (int)0x29,
            Reserved2 = (int)0x30
        }
    
        internal enum StateChangeAction
        {
            Enable = 1,
            Disable = 2,
            PropChange = 3,
            Start = 4,
            Stop = 5
        }
    
        [Flags()]
        internal enum Scopes
        {
            Global = 1,
            ConfigSpecific = 2,
            ConfigGeneral = 4
        }
    
        internal enum SetupApiError
        {
            NoAssociatedClass = unchecked((int)0xe0000200),
            ClassMismatch = unchecked((int)0xe0000201),
            DuplicateFound = unchecked((int)0xe0000202),
            NoDriverSelected = unchecked((int)0xe0000203),
            KeyDoesNotExist = unchecked((int)0xe0000204),
            InvalidDevinstName = unchecked((int)0xe0000205),
            InvalidClass = unchecked((int)0xe0000206),
            DevinstAlreadyExists = unchecked((int)0xe0000207),
            DevinfoNotRegistered = unchecked((int)0xe0000208),
            InvalidRegProperty = unchecked((int)0xe0000209),
            NoInf = unchecked((int)0xe000020a),
            NoSuchHDevinst = unchecked((int)0xe000020b),
            CantLoadClassIcon = unchecked((int)0xe000020c),
            InvalidClassInstaller = unchecked((int)0xe000020d),
            DiDoDefault = unchecked((int)0xe000020e),
            DiNoFileCopy = unchecked((int)0xe000020f),
            InvalidHwProfile = unchecked((int)0xe0000210),
            NoDeviceSelected = unchecked((int)0xe0000211),
            DevinfolistLocked = unchecked((int)0xe0000212),
            DevinfodataLocked = unchecked((int)0xe0000213),
            DiBadPath = unchecked((int)0xe0000214),
            NoClassInstallParams = unchecked((int)0xe0000215),
            FileQueueLocked = unchecked((int)0xe0000216),
            BadServiceInstallSect = unchecked((int)0xe0000217),
            NoClassDriverList = unchecked((int)0xe0000218),
            NoAssociatedService = unchecked((int)0xe0000219),
            NoDefaultDeviceInterface = unchecked((int)0xe000021a),
            DeviceInterfaceActive = unchecked((int)0xe000021b),
            DeviceInterfaceRemoved = unchecked((int)0xe000021c),
            BadInterfaceInstallSect = unchecked((int)0xe000021d),
            NoSuchInterfaceClass = unchecked((int)0xe000021e),
            InvalidReferenceString = unchecked((int)0xe000021f),
            InvalidMachineName = unchecked((int)0xe0000220),
            RemoteCommFailure = unchecked((int)0xe0000221),
            MachineUnavailable = unchecked((int)0xe0000222),
            NoConfigMgrServices = unchecked((int)0xe0000223),
            InvalidPropPageProvider = unchecked((int)0xe0000224),
            NoSuchDeviceInterface = unchecked((int)0xe0000225),
            DiPostProcessingRequired = unchecked((int)0xe0000226),
            InvalidCOInstaller = unchecked((int)0xe0000227),
            NoCompatDrivers = unchecked((int)0xe0000228),
            NoDeviceIcon = unchecked((int)0xe0000229),
            InvalidInfLogConfig = unchecked((int)0xe000022a),
            DiDontInstall = unchecked((int)0xe000022b),
            InvalidFilterDriver = unchecked((int)0xe000022c),
            NonWindowsNTDriver = unchecked((int)0xe000022d),
            NonWindowsDriver = unchecked((int)0xe000022e),
            NoCatalogForOemInf = unchecked((int)0xe000022f),
            DevInstallQueueNonNative = unchecked((int)0xe0000230),
            NotDisableable = unchecked((int)0xe0000231),
            CantRemoveDevinst = unchecked((int)0xe0000232),
            InvalidTarget = unchecked((int)0xe0000233),
            DriverNonNative = unchecked((int)0xe0000234),
            InWow64 = unchecked((int)0xe0000235),
            SetSystemRestorePoint = unchecked((int)0xe0000236),
            IncorrectlyCopiedInf = unchecked((int)0xe0000237),
            SceDisabled = unchecked((int)0xe0000238),
            UnknownException = unchecked((int)0xe0000239),
            PnpRegistryError = unchecked((int)0xe000023a),
            RemoteRequestUnsupported = unchecked((int)0xe000023b),
            NotAnInstalledOemInf = unchecked((int)0xe000023c),
            InfInUseByDevices = unchecked((int)0xe000023d),
            DiFunctionObsolete = unchecked((int)0xe000023e),
            NoAuthenticodeCatalog = unchecked((int)0xe000023f),
            AuthenticodeDisallowed = unchecked((int)0xe0000240),
            AuthenticodeTrustedPublisher = unchecked((int)0xe0000241),
            AuthenticodeTrustNotEstablished = unchecked((int)0xe0000242),
            AuthenticodePublisherNotTrusted = unchecked((int)0xe0000243),
            SignatureOSAttributeMismatch = unchecked((int)0xe0000244),
            OnlyValidateViaAuthenticode = unchecked((int)0xe0000245)
        }
    
        [StructLayout(LayoutKind.Sequential)]
        internal struct DeviceInfoData
        {
            public int Size;
            public Guid ClassGuid;
            public int DevInst;
            public IntPtr Reserved;
        }
    
        [StructLayout(LayoutKind.Sequential)]
        internal struct PropertyChangeParameters
        {
            public int Size;
            // part of header. It's flattened out into 1 structure.
            public DiFunction DiFunction;
            public StateChangeAction StateChange;
            public Scopes Scope;
            public int HwProfile;
        }
    
        internal class NativeMethods
        {
    
            private const string setupapi = "setupapi.dll";
    
            private NativeMethods()
            {
            }
    
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiCallClassInstaller(DiFunction installFunction, SafeDeviceInfoSetHandle deviceInfoSet, [In()]
    ref DeviceInfoData deviceInfoData);
    
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiEnumDeviceInfo(SafeDeviceInfoSetHandle deviceInfoSet, int memberIndex, ref DeviceInfoData deviceInfoData);
    
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
            public static extern SafeDeviceInfoSetHandle SetupDiGetClassDevs([In()]
    ref Guid classGuid, [MarshalAs(UnmanagedType.LPWStr)]
    string enumerator, IntPtr hwndParent, SetupDiGetClassDevsFlags flags);
    
            /*
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiGetDeviceInstanceId(SafeDeviceInfoSetHandle deviceInfoSet, [In()]
    ref DeviceInfoData did, [MarshalAs(UnmanagedType.LPTStr)]
    StringBuilder deviceInstanceId, int deviceInstanceIdSize, [Out()]
    ref int requiredSize);
            */
            [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiGetDeviceInstanceId(
               IntPtr DeviceInfoSet,
               ref DeviceInfoData did,
               [MarshalAs(UnmanagedType.LPTStr)] StringBuilder DeviceInstanceId,
               int DeviceInstanceIdSize,
               out int RequiredSize
            );
    
            [SuppressUnmanagedCodeSecurity()]
            [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
    
            [DllImport(setupapi, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool SetupDiSetClassInstallParams(SafeDeviceInfoSetHandle deviceInfoSet, [In()]
    ref DeviceInfoData deviceInfoData, [In()]
    ref PropertyChangeParameters classInstallParams, int classInstallParamsSize);
    
        }
    
        internal class SafeDeviceInfoSetHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
    
            public SafeDeviceInfoSetHandle()
                : base(true)
            {
            }
    
            protected override bool ReleaseHandle()
            {
                return NativeMethods.SetupDiDestroyDeviceInfoList(this.handle);
            }
    
        }
    
        public sealed class DeviceHelper
        {
    
            private DeviceHelper()
            {
            }
    
            /// <summary>
            /// Enable or disable a device.
            /// </summary>
            /// <param name="classGuid">The class guid of the device. Available in the device manager.</param>
            /// <param name="instanceId">The device instance id of the device. Available in the device manager.</param>
            /// <param name="enable">True to enable, False to disable.</param>
            /// <remarks>Will throw an exception if the device is not Disableable.</remarks>
            public static void SetDeviceEnabled(Guid classGuid, string instanceId, bool enable)
            {
                SafeDeviceInfoSetHandle diSetHandle = null;
                try
                {
                    // Get the handle to a device information set for all devices matching classGuid that are present on the 
                    // system.
                    diSetHandle = NativeMethods.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, SetupDiGetClassDevsFlags.Present);
                    // Get the device information data for each matching device.
                    DeviceInfoData[] diData = GetDeviceInfoData(diSetHandle);
                    // Find the index of our instance. i.e. the touchpad mouse - I have 3 mice attached...
                    int index = GetIndexOfInstance(diSetHandle, diData, instanceId);
                    // Disable...
                    EnableDevice(diSetHandle, diData[index], enable);
                }
                finally
                {
                    if (diSetHandle != null)
                    {
                        if (diSetHandle.IsClosed == false)
                        {
                            diSetHandle.Close();
                        }
                        diSetHandle.Dispose();
                    }
                }
            }
    
            private static DeviceInfoData[] GetDeviceInfoData(SafeDeviceInfoSetHandle handle)
            {
                List<DeviceInfoData> data = new List<DeviceInfoData>();
                DeviceInfoData did = new DeviceInfoData();
                int didSize = Marshal.SizeOf(did);
                did.Size = didSize;
                int index = 0;
                while (NativeMethods.SetupDiEnumDeviceInfo(handle, index, ref did))
                {
                    data.Add(did);
                    index += 1;
                    did = new DeviceInfoData();
                    did.Size = didSize;
                }
                return data.ToArray();
            }
    
            // Find the index of the particular DeviceInfoData for the instanceId.
            private static int GetIndexOfInstance(SafeDeviceInfoSetHandle handle, DeviceInfoData[] diData, string instanceId)
            {
                const int ERROR_INSUFFICIENT_BUFFER = 122;
                for (int index = 0; index <= diData.Length - 1; index++)
                {
                    StringBuilder sb = new StringBuilder(1);
                    int requiredSize = 0;
                    bool result = NativeMethods.SetupDiGetDeviceInstanceId(handle.DangerousGetHandle(), ref diData[index], sb, sb.Capacity, out requiredSize);
                    if (result == false && Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
                    {
                        sb.Capacity = requiredSize;
                        result = NativeMethods.SetupDiGetDeviceInstanceId(handle.DangerousGetHandle(), ref diData[index], sb, sb.Capacity, out requiredSize);
                    }
                    if (result == false)
                        throw new Win32Exception();
                    if (instanceId.Equals(sb.ToString()))
                    {
                        return index;
                    }
                }
                // not found
                return -1;
            }
    
            // enable/disable...
            private static void EnableDevice(SafeDeviceInfoSetHandle handle, DeviceInfoData diData, bool enable)
            {
                PropertyChangeParameters @params = new PropertyChangeParameters();
                // The size is just the size of the header, but we've flattened the structure.
                // The header comprises the first two fields, both integer.
                @params.Size = 8;
                @params.DiFunction = DiFunction.PropertyChange;
                @params.Scope = Scopes.Global;
                if (enable)
                {
                    @params.StateChange = StateChangeAction.Enable;
                }
                else
                {
                    @params.StateChange = StateChangeAction.Disable;
                }
    
                bool result = NativeMethods.SetupDiSetClassInstallParams(handle, ref diData, ref @params, Marshal.SizeOf(@params));
                if (result == false) throw new Win32Exception();
                result = NativeMethods.SetupDiCallClassInstaller(DiFunction.PropertyChange, handle, ref diData);
                if (result == false)
                {
                    int err = Marshal.GetLastWin32Error();
                    if (err == (int)SetupApiError.NotDisableable)
                        throw new ArgumentException("Device can't be disabled (programmatically or in Device Manager).");
                    else if (err >= (int)SetupApiError.NoAssociatedClass && err <= (int)SetupApiError.OnlyValidateViaAuthenticode)
                        throw new Win32Exception("SetupAPI error: " + ((SetupApiError)err).ToString());
                    else
                        throw new Win32Exception();
                }
            }
        }
    }
    

    如果您手头有 GUID 和 instancePath(即设备管理器中的路径),则可以按如下方式禁用设备:

    Guid deviceGuid = new Guid("{4D36E96F-E325-11CE-BFC1-08002BE10318}");//думаю это можно захардкодить
    string instancePath = @"HID\VID_062A&PID_4101&MI_01&COL01\8&14EA75C&0&0000";//это захардкодить вряд ли выйдет, нужно будет поискать в девайс менеджере через шарп нужный путь
    
    DeviceHelper.SetDeviceEnabled(deviceGuid, instancePath, false); //фалс отключает девайс / тру - включает
    

    конкретно этим кодом и конкретно этими значениями я себе отключил мышку для теста :)

    Но этим способом так же под вопросом выйдет ли отключить конкретный девайс. Не все девайсы это поддерживают.

    Оригинал кода нашел вот здесь: https://stackoverflow.com/questions/1438371/win32-api-function-to-programmatically-enable-disable-device

    Так же, судя по тексту, нужно твою прогу компилить именно в х64 (в той платформе -- в которой у тебя операционка).

    С поиском GUID девайса все довольно просто: девайс менеджер -> ищешь нужный девайс -> пропертиз -> Ивентс -> в блоке инфрпмации будет "Class Guid".

    с поиском программного пути конкретного девайса разберешся сам. Вопрос стоял об отключении девайса :)


    А можно ли отключать питание

    Внезапно (для меня лично), но это возможно.

    https://stackoverflow.com/questions/14690157/turn-off-power-to-usb-port-programmatically

    Как видно по второму ответу прога DevManView.exe умеет отключать в рантайме. Значит это ВОЗМОЖНО (лично я думал что это блокировано на хардварном уровне) . Но как сделать это напрямую из шарпа я не подскажу. :) Только если использовать консольные возможности этой проги -- снова таки, по линке описано как.

    блокировать конкретный USB порт без перезагрузок?

    Не понимаю что такое "блокировать". Если ты про просто дисейбл устройства как через девайс менеджер - то реализация выше. Без перезагрузок.

    Если ты про "блокировать ручное включение девайса" -- ты можешь просто устроить слежку за тем, не включили ли этот девайс без твоего разрешения в отдельном потоке и автоматом отключать. Криво, но будет работать как тебе нужно.

    Или же отключать не отключаемые устройства?

    Наверное они на то и отключаемые, что бы их не отключали. Вряд ли.

    Только если питание рубонуть.

    UPD: как обозначил MSDN.WhiteKnight в коментариях, то вполне возможно что неотключаемые устройства являются "составными". То есть если ты отключишь несколько дочерних, то и это неотключаемое будет отключено.

    • 9
  2. Yaroslav
    2020-11-04T02:00:36Z2020-11-04T02:00:36Z

    Я пришел к двум вариантам:

    Вариант №1: отключать USB порты можно через regedit

    public void EnableUSB() => Regedit(3);
    
    public void DisableUSB() => Regedit(4);
    
    // key - это параметр включения или отключения
    // 4 - отключенно
    // 3 - включенно
    public static void Regedit(Int16 key)
    {
        const String keyname = @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR";
        Microsoft.Win32.Registry.SetValue(keyname, "Start", key);
    }
    

    Вариант №2: с помощью утилиты DevManView.exe(freeware):

    转到设备管理器并找出将切断电源的设备的名称,或者您可以通过编程方式获取设备名称。

    public void EnableDevice(String nameDevice) => DevManView(nameDevice, "enable");
    
    public void DisableDevice(String nameDevice) => DevManView(nameDevice, "disable");
    
    public static void DevManView(String nameDevice, String command)
    {
        Process devManViewProc = new Process();
        devManViewProc.StartInfo.FileName = @"<path to DevManView.exe>\DevManView.exe";
        devManViewProc.StartInfo.Arguments = $"/{command} \"{nameDevice}\"";
        devManViewProc.Start();
        devManViewProc.WaitForExit();
    }
    
    • 3

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    是否可以在 C++ 中继承类 <---> 结构?

    • 2 个回答
  • Marko Smith

    这种神经网络架构适合文本分类吗?

    • 1 个回答
  • Marko Smith

    为什么分配的工作方式不同?

    • 3 个回答
  • Marko Smith

    控制台中的光标坐标

    • 1 个回答
  • Marko Smith

    如何在 C++ 中删除类的实例?

    • 4 个回答
  • Marko Smith

    点是否属于线段的问题

    • 2 个回答
  • Marko Smith

    json结构错误

    • 1 个回答
  • Marko Smith

    ServiceWorker 中的“获取”事件

    • 1 个回答
  • Marko Smith

    c ++控制台应用程序exe文件[重复]

    • 1 个回答
  • Marko Smith

    按多列从sql表中选择

    • 1 个回答
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Suvitruf - Andrei Apanasik 什么是空? 2020-08-21 01:48:09 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5