返回顶部

收藏

C#监控是否有u盘插入

更多

C#监控是否有u盘插入,同时可以监控其它驱动器的变化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsApplication16
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        [StructLayout(LayoutKind.Sequential)]
        public struct DEV_BROADCAST_VOLUME
        {
            public int dbcv_size;
            public int dbcv_devicetype;
            public int dbcv_reserved;
            public int dbcv_unitmask;
        }

        protected override void WndProc(ref Message m)
        {
            // 发生设备变动
            const int WM_DEVICECHANGE = 0x0219;
            // 系统检测到一个新设备
            const int DBT_DEVICEARRIVAL = 0x8000;
            // 系统完成移除一个设备
            const int DBT_DEVICEREMOVECOMPLETE = 0x8001;
            // 逻辑卷标
            const int DBT_DEVTYP_VOLUME = 0x00000002;

            switch (m.Msg)
            {
                case WM_DEVICECHANGE:
                    switch (m.WParam.ToInt32())
                    {
                        case DBT_DEVICEARRIVAL:
                            int devType = Marshal.ReadInt32(m.LParam, 4);
                            if (devType == DBT_DEVTYP_VOLUME)
                            {
                                DEV_BROADCAST_VOLUME vol;
                                vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(
                                    m.LParam, typeof(DEV_BROADCAST_VOLUME));

                                MessageBox.Show(vol.dbcv_unitmask.ToString("x"));
                            }
                            break;
                        case DBT_DEVICEREMOVECOMPLETE:
                            MessageBox.Show("Removal");
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

    }
}
//该片段来自于http://outofmemory.cn

标签:c#,.net,系统

收藏

0人收藏

支持

1

反对

0

发表评论