欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#判断U盘插拔,获取盘符

程序员文章站 2022-05-06 08:09:48
...

C#判断U盘插拔,获取盘符

标题相关变量


        public const int WM_DEVICECHANGE = 0x219;

        public const int DBT_DEVICEARRIVAL = 0x8000;

        public const int DBT_CONFIGCHANGECANCELED = 0x0019;

        public const int DBT_CONFIGCHANGED = 0x0018;

        public const int DBT_CUSTOMEVENT = 0x8006;

        public const int DBT_DEVICEQUERYREMOVE = 0x8001;

        public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;

        public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;

        public const int DBT_DEVICEREMOVEPENDING = 0x8003;

        public const int DBT_DEVICETYPESPECIFIC = 0x8005;

        public const int DBT_DEVNODES_CHANGED = 0x0007;

        public const int DBT_QUERYCHANGECONFIG = 0x0017;

        public const int DBT_USERDEFINED = 0xFFFF;

处理方法

protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == WM_DEVICECHANGE)
                {
                    switch (m.WParam.ToInt32())
                    {
                        case WM_DEVICECHANGE:
                            break;

                        case DBT_DEVICEARRIVAL:   //U盘插入,定位在第一个插入的U盘
                            DriveInfo[] s = DriveInfo.GetDrives();
                            foreach (DriveInfo drive in s)
                            {
                                if (drive.DriveType == DriveType.Removable)
                                {
                                    USBFlashDiskPath = drive.Name.ToString();
                                    OpenFilebtn.Enabled = true;
                                    break;
                                }
                            }
                            break;

                        case DBT_DEVICEREMOVECOMPLETE:   //U盘卸载,判断是否还有U盘
                            USBFlashDiskPath = "";
                            DriveInfo[] a = DriveInfo.GetDrives();
                            foreach (DriveInfo drive in a)
                            {
                                if (drive.DriveType == DriveType.Removable)
                                {
                                    USBFlashDiskPath = drive.Name.ToString();
                                    break;
                                }
                              
                            }
                            if (USBFlashDiskPath == "")
                            {
                                OpenFilebtn.Enabled = false;
                            }
                            break;

                        default:
                            break;

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            base.WndProc(ref m);

        }