如何在C#中重新加载USB磁盘?

如何在C#中重新加载USB磁盘?,c#,.net,windows,usb,C#,.net,Windows,Usb,我有一个关于USB磁盘的项目。我已经在代码中实现了弹出USB磁盘。但是我想知道如何重新加载它?谁能给我一些建议吗。 最好是一个例子!thxMicrosoft提供了一个工具(devcon),可用于实现设备管理器的功能 以下命令用于删除特定设备(假设您的设备名为Kingston) 这会导致设备被禁用。因此,它不再可用。 命令“重新扫描”将启用设备 > devcon rescan 可以通过Process.Start()方法执行此命令。 这不适用于标记为“安全移除”的设备。我已通过这种方式解决了

我有一个关于USB磁盘的项目。我已经在代码中实现了弹出USB磁盘。但是我想知道如何重新加载它?谁能给我一些建议吗。 最好是一个例子!thx

Microsoft提供了一个工具(devcon),可用于实现设备管理器的功能

以下命令用于删除特定设备(假设您的设备名为Kingston)

这会导致设备被禁用。因此,它不再可用。 命令“重新扫描”将启用设备

> devcon rescan
可以通过Process.Start()方法执行此命令。
这不适用于标记为“安全移除”的设备。

我已通过这种方式解决了此问题,流程是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

private void btnenable_Click(object sender, EventArgs e)
{
const string keyName = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR";

// int tLong = (int )Registry.GetValue(keyName, "Start",0);
Registry.SetValue(keyName, "Start", "00000003");
MessageBox.Show("USB MassStorage Enabled"); 

}

private void btndisable_Click(object sender, EventArgs e)
{
const string keyName = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR";

// int tLong = (int )Registry.GetValue(keyName, "Start",0);
Registry.SetValue(keyName, "Start", "00000004");
MessageBox.Show("USB MassStorage Disabled"); 
}
win32.cs

using System;
使用System.Collections.Generic; 使用系统文本; 使用System.Runtime.InteropServices

命名空间系统设备 { [StructLayout(LayoutKind.Sequential)] 公共结构SP\u广播\u句柄 { 公共int dbch_尺寸; 公共int dbch_设备类型; 公共int dbch_保留; 公共IntPtr dbch_句柄; 公共IntPtr dbch_hdevnotify; 公共Guid dbch_eventguid; 公共长dbch_name offset; 公共字节dbch_数据; 公共字节dbch_data1; }

}

在win32.cs中有一些控制硬件的函数

功能状态更改(bool Enable、int SelectedItem、IntPtr DevInfo)用于控制硬件启动或停止。 有三个参数。启用为true时,此函数使id为SelectedItem的硬件启动,如果为false则停止。我在代码中获取id:

 Guid classGuid = Guid.Empty;
        IntPtr hDevInfo = Win32.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Win32.DIGCF_ALLCLASSES | Win32.DIGCF_PRESENT);
        if (hDevInfo.ToInt32() == Win32.INVALID_HANDLE_VALUE)
        {
            Console.WriteLine("read hardware information error");
        }
        else
        {
            int i = 0;
            StringBuilder deviceName = new StringBuilder();
            deviceName.Capacity = Win32.MAX_DEV_LEN;
            do
            {
                SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA();
                devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
                devInfoData.classGuid = Guid.Empty;
                devInfoData.devInst = 0;
                devInfoData.reserved = IntPtr.Zero;
                bool result = Win32.SetupDiEnumDeviceInfo(hDevInfo, i, devInfoData);
                if (false == result)
                {
                    break;
                }
                Console.WriteLine("Device: {0}", i);
                Console.WriteLine("\tGuid={0}", devInfoData.classGuid);
                Console.WriteLine("\tName={0}", Win32.GetClassNameFromGuid(devInfoData.classGuid));
                Console.WriteLine("\tDescription={0}", Win32.GetClassDescriptionFromGuid(devInfoData.classGuid));}
[StructLayout(LayoutKind.Sequential)]
public class DEV_BROADCAST_DEVICEINTERFACE
{
    public int dbcc_size;
    public int dbcc_devicetype;
    public int dbcc_reserved;
}

[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid classGuid;
    public int devInst;
    public IntPtr reserved;
};

[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINSTALL_PARAMS
{
    public int cbSize;
    public int Flags;
    public int FlagsEx;
    public IntPtr hwndParent;
    public IntPtr InstallMsgHandler;
    public IntPtr InstallMsgHandlerContext;
    public IntPtr FileQueue;
    public IntPtr ClassInstallReserved;
    public int Reserved;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string DriverPath;
};

[StructLayout(LayoutKind.Sequential)]
public class SP_PROPCHANGE_PARAMS
{
    public SP_CLASSINSTALL_HEADER ClassInstallHeader = new SP_CLASSINSTALL_HEADER();
    public int StateChange;
    public int Scope;
    public int HwProfile;
};

[StructLayout(LayoutKind.Sequential)]
public class SP_CLASSINSTALL_HEADER
{
    public int cbSize;
    public int InstallFunction;
};

public class Win32
{
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, DEV_BROADCAST_DEVICEINTERFACE NotificationFilter, UInt32 Flags);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern UInt32 UnregisterDeviceNotification(IntPtr hHandle);

    [DllImport("setupapi.dll", SetLastError = true)]
    public static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
        [MarshalAs(UnmanagedType.LPStr)]String Enumerator, IntPtr hwndParent, Int32 Flags);

    [DllImport("setupapi.dll")]
    public static extern IntPtr SetupDiGetClassDevsEx(ref Guid ClassGuid,
        [MarshalAs(UnmanagedType.LPStr)]String Enumerator,
        IntPtr hwndParent, Int32 Flags, IntPtr DeviceInfoSet,
        [MarshalAs(UnmanagedType.LPStr)]String MachineName,
        IntPtr Reserved);

    [DllImport("setupapi.dll", SetLastError = true)]
    public static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr lpInfoSet);

    [DllImport("setupapi.dll", SetLastError = true)]
    public static extern Boolean SetupDiEnumDeviceInfo(IntPtr lpInfoSet, Int32 dwIndex, SP_DEVINFO_DATA devInfoData);

    [DllImport("setupapi.dll", SetLastError = true)]
    public static extern Boolean SetupDiGetDeviceRegistryProperty(IntPtr lpInfoSet, SP_DEVINFO_DATA DeviceInfoData, UInt32 Property,
        UInt32 PropertyRegDataType, StringBuilder PropertyBuffer, UInt32 PropertyBufferSize, IntPtr RequiredSize);

    [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern Boolean SetupDiSetClassInstallParams(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, SP_PROPCHANGE_PARAMS ClassInstallParams, int ClassInstallParamsSize);

    [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
    public static extern Boolean SetupDiCallClassInstaller(UInt32 InstallFunction, IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData);

    [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
    public static extern Boolean SetupDiClassNameFromGuid(ref Guid ClassGuid, StringBuilder className, Int32 ClassNameSize, ref Int32 RequiredSize);

    [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
    public static extern Boolean SetupDiGetClassDescription(ref Guid ClassGuid, StringBuilder classDescription, Int32 ClassDescriptionSize, ref Int32 RequiredSize);

    [DllImport("setupapi.dll", CharSet = CharSet.Auto)]
    public static extern Boolean SetupDiGetDeviceInstanceId(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData, StringBuilder DeviceInstanceId, Int32 DeviceInstanceIdSize, ref Int32 RequiredSize);

    public const int DIGCF_ALLCLASSES = (0x00000004);
    public const int DIGCF_PRESENT = (0x00000002);
    public const int INVALID_HANDLE_VALUE = -1;
    public const int SPDRP_DEVICEDESC = (0x00000000);
    public const int MAX_DEV_LEN = 200;
    public const int DEVICE_NOTIFY_WINDOW_HANDLE = (0x00000000);
    public const int DEVICE_NOTIFY_SERVICE_HANDLE = (0x00000001);
    public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = (0x00000004);
    public const int DBT_DEVTYP_DEVICEINTERFACE = (0x00000005);
    public const int DBT_DEVNODES_CHANGED = (0x0007);
    public const int WM_DEVICECHANGE = (0x0219);
    public const int DIF_PROPERTYCHANGE = (0x00000012);
    public const int DICS_FLAG_GLOBAL = (0x00000001);
    public const int DICS_FLAG_CONFIGSPECIFIC = (0x00000002);
    public const int DICS_ENABLE = (0x00000001);
    public const int DICS_DISABLE = (0x00000002);

    public static bool StateChange(bool Enable, int SelectedItem, IntPtr DevInfo)
    {
        bool result = false;
        SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA(); ;
        devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
        if (true == SetupDiEnumDeviceInfo(DevInfo, SelectedItem, devInfoData))
        {
            SP_PROPCHANGE_PARAMS pcp = new SP_PROPCHANGE_PARAMS(); ;
            pcp.ClassInstallHeader.cbSize = Marshal.SizeOf(typeof(SP_CLASSINSTALL_HEADER));
            pcp.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
            pcp.Scope = DICS_FLAG_GLOBAL;
            pcp.StateChange = (Enable ? DICS_ENABLE : DICS_DISABLE);
            if (true == SetupDiSetClassInstallParams(DevInfo, devInfoData, pcp, Marshal.SizeOf(pcp)))
            {
                if (true == SetupDiCallClassInstaller(DIF_PROPERTYCHANGE, DevInfo, devInfoData))
                {
                    result = true;
                }
            }
        }
        return result;
    }

    public static String GetClassNameFromGuid(Guid guid)
    {
        String result = String.Empty;
        StringBuilder className = new StringBuilder();
        Int32 iRequiredSize = 0;
        Int32 iSize = 0;
        bool b = SetupDiClassNameFromGuid(ref guid, className, iSize, ref iRequiredSize);

        className = new StringBuilder(iRequiredSize);
        iSize = iRequiredSize;

        b = SetupDiClassNameFromGuid(ref guid, className, iSize, ref iRequiredSize);
        if (true == b)
        {
            result = className.ToString();
        }
        return result;
    }
    public static String GetClassDescriptionFromGuid(Guid guid)
    {
        String result = String.Empty;
        StringBuilder classDesc = new StringBuilder(0);
        Int32 iRequiredSize = 0;
        Int32 iSize = 0;
        bool b = SetupDiGetClassDescription(ref guid, classDesc, iSize, ref iRequiredSize);

        classDesc = new StringBuilder(iRequiredSize);
        iSize = iRequiredSize;

        b = SetupDiGetClassDescription(ref guid, classDesc, iSize, ref iRequiredSize);
        if (true == b)
        {
            result = classDesc.ToString();
        }
        return result;
    }

    public static String GetDeviceInstanceId(IntPtr DeviceInfoSet, SP_DEVINFO_DATA DeviceInfoData)
    {
        String result = String.Empty;
        StringBuilder id = new StringBuilder(0);
        Int32 iRequiredSize = 0;
        Int32 iSize = 0;
        bool b = SetupDiGetDeviceInstanceId(DeviceInfoSet, DeviceInfoData, id, iSize, ref iRequiredSize);

        id = new StringBuilder(iRequiredSize);
        iSize = iRequiredSize;

        b = SetupDiGetDeviceInstanceId(DeviceInfoSet, DeviceInfoData, id, iSize, ref iRequiredSize);
        if (true == b)
        {
            result = id.ToString();
        }
        return result;
    }
}
 Guid classGuid = Guid.Empty;
        IntPtr hDevInfo = Win32.SetupDiGetClassDevs(ref classGuid, null, IntPtr.Zero, Win32.DIGCF_ALLCLASSES | Win32.DIGCF_PRESENT);
        if (hDevInfo.ToInt32() == Win32.INVALID_HANDLE_VALUE)
        {
            Console.WriteLine("read hardware information error");
        }
        else
        {
            int i = 0;
            StringBuilder deviceName = new StringBuilder();
            deviceName.Capacity = Win32.MAX_DEV_LEN;
            do
            {
                SP_DEVINFO_DATA devInfoData = new SP_DEVINFO_DATA();
                devInfoData.cbSize = Marshal.SizeOf(typeof(SP_DEVINFO_DATA));
                devInfoData.classGuid = Guid.Empty;
                devInfoData.devInst = 0;
                devInfoData.reserved = IntPtr.Zero;
                bool result = Win32.SetupDiEnumDeviceInfo(hDevInfo, i, devInfoData);
                if (false == result)
                {
                    break;
                }
                Console.WriteLine("Device: {0}", i);
                Console.WriteLine("\tGuid={0}", devInfoData.classGuid);
                Console.WriteLine("\tName={0}", Win32.GetClassNameFromGuid(devInfoData.classGuid));
                Console.WriteLine("\tDescription={0}", Win32.GetClassDescriptionFromGuid(devInfoData.classGuid));}