本文最后更新于 149 天前,其中的信息可能已经有所发展或是发生改变。
public const int WM_DEVICECHANGE = 0x219;//U盘插入后,OS的底层会自动检测到,然后向应用程序发送“硬件设备状态改变“的消息 public const int DBT_DEVICEARRIVAL = 0x8000; //就是用来表示U盘可用的。一个设备或媒体已被插入一块,现在可用。 public const int DBT_DEVICEREMOVECOMPLETE = 0x8004; //一个设备或媒体片已被删除。 protected override void WndProc(ref Message m) { if (collForm != null && collectForm.Workstation != null) { if (m.Msg == WM_DEVICECHANGE)//WM_DEVICECHANGE { switch (m.WParam.ToInt32()) { case DBT_DEVICEARRIVAL://DBT_DEVICEARRIVAL { if (Form1.IsAutoDisk) { string panfu = ""; int devType1 = Marshal.ReadInt32(m.LParam, 4); if (devType1 == DBT_DEVTYP_VOLUME) { DEV_BROADCAST_VOLUME vol; vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME)); ID = vol.dbcv_unitmask.ToString("x"); //Sunny.UI.UIMessageBox.ShowInfo(IO(ID) + "盘插入!", false, true); panfu = IO(ID); //collForm.flowLayoutPanel1.Controls.Add(new UserControl1()); collForm.flowLayoutPanel1.Controls.Add(new FormControl.CardControl(panfu) { Name = ID, IsCheckAnJian = collForm.cbAnJian.Checked }); collForm.cbAnJian.Enabled = false; } } } break; case DBT_DEVICEREMOVECOMPLETE://DBT_DEVICEREMOVECOMPLETE 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)); ID = vol.dbcv_unitmask.ToString("x"); collForm.flowLayoutPanel1.Controls.RemoveByKey(ID); if (collForm.flowLayoutPanel1.Controls.Count == 0) { collForm.cbAnJian.Enabled = true; } } //MessageBox.Show("设备拔出"); break; case 0x7: System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = "GetDevicInfo.exe";//需要启动的程序名 p.StartInfo.CreateNoWindow = true; p.Start();//启动 Thread.Sleep(1000); if (!p.HasExited)//判断是否运行结束 { p.Kill(); } break; default: Console.WriteLine(m.WParam.ToInt32()); break; } } } base.WndProc(ref m); }