C #. net usb flash drive plugging monitoring

Source: Internet
Author: User

C #. net usb flash drive plugging monitoring

[1] knowledge points involved

1) windows message processing functions

protected override void WndProc(ref Message m)


System messages sent from system hardware changes that Capture Messages


2) hardware information

DriveInfo

[2] core functions

Message constant:

////// Windows message constant ///Class CWndProMsgConst {public const int WM_DEVICECHANGE = 0x219; // system message issued by system hardware change public const int DBT_DEVICEARRIVAL = 0x8000; // The device detection is complete, 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; // uninstall the device or remove the public const int DBT_DEVICEREMOVEPENDING = 0x8003; public const int DBT_DEVICETYPEHANGED = 0x0007; public const int DBT_QUERYCHANGSPECIFIC = 0x8005; public const int DBT_DEVNODES_CECONFIG = 0x0017; public const int DBT_USERDEFINED = 0 xFFFF ;}

Scan function:

////// Scan U Port Devices ///Private void ScanUSBDisk () {_ usbdiskList. clear (); DriveInfo [] drives = DriveInfo. getDrives (); foreach (DriveInfo drive in drives) {if (drive. driveType = DriveType. removable )&&! Drive. name. substring (0, 1 ). equals ("A") {try {_ usbdiskList. add (drive. name);} catch {MessageBox. show ("the current disk cannot be identified correctly. Please try again! "," Prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );}}}}

Message Processing functions:

Public void FillData (Form form, Message m, ListBox listbox) {_ listbox = listbox; _ form = form; try {if (m. msg = CWndProMsgConst. WM_DEVICECHANGE) // system message sent by system hardware Change {switch (m. WParam. toInt32 () {case CWndProMsgConst. WM_DEVICECHANGE: break; // The device detection is complete. You can use case CWndProMsgConst. DBT_DEVICEARRIVAL: {ScanUSBDisk (); _ listbox. items. clear (); foreach (string str in _ usbdiskList) {_ listbox. items. add (str) ;} Break; // detach the device or remove case CWndProMsgConst. DBT_DEVICEREMOVECOMPLETE: {ScanUSBDisk (); _ listbox. items. clear (); foreach (string str in _ usbdiskList) {_ listbox. items. add (str) ;}} break; default: break ;}} catch (Exception ex) {MessageBox. show ("the current disk cannot be identified correctly. Please try again! "," Prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );}}

Complete CS encapsulation file:

Using System; using System. Collections. Generic; using System. Text; using System. Windows. Forms; using System. Threading; using System. IO; namespace USBMonitor {////// USB plugging monitoring class ///Public class CUSBMonitor {private delegate void SetTextCallback (string s); private IList
 
  
_ UsbdiskList = new List
  
   
(); Private ListBox _ listbox = null; private Form _ form = null; public CUSBMonitor () {System. timers. timer timer = new System. timers. timer (1000); timer. enabled = true; // timer occurs when the interval is reached. elapsed + = new System. timers. elapsedEventHandler (TimerList); timer. autoReset = false; // only triggered once after the first interval ends} public void FillData (Form form, Message m, ListBox listbox) {_ listbox = listbox; _ form = Form; try {if (m. ms G = CWndProMsgConst. WM_DEVICECHANGE) // system message sent by system hardware Change {switch (m. WParam. toInt32 () {case CWndProMsgConst. WM_DEVICECHANGE: break; // The device detection is complete. You can use case CWndProMsgConst. DBT_DEVICEARRIVAL: {ScanUSBDisk (); _ listbox. items. clear (); foreach (string str in _ usbdiskList) {_ listbox. items. add (str) ;}} break; // uninstall the device or unplug case CWndProMsgConst. DBT_DEVICEREMOVECOMPLETE: {ScanUSBDisk (); _ listbox. items. clear (); Foreach (string str in _ usbdiskList) {_ listbox. items. add (str) ;}} break; default: break ;}} catch (Exception ex) {MessageBox. show ("the current disk cannot be identified correctly. Please try again! "," Prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );}}///
   /// Set the USB list ///Void TimerList (object sender, System. Timers. ElapsedEventArgs e) {ScanUSBDisk (); foreach (string str in _ usbdiskList) {SetText (str );}}///
   /// Scan U Port Devices ///Private void ScanUSBDisk () {_ usbdiskList. clear (); DriveInfo [] drives = DriveInfo. getDrives (); foreach (DriveInfo drive in drives) {if (drive. driveType = DriveType. removable )&&! Drive. name. substring (0, 1 ). equals ("A") {try {_ usbdiskList. add (drive. name);} catch {MessageBox. show ("the current disk cannot be identified correctly. Please try again! "," Prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );}}}}///
   /// Set List //////
   NamePublic void SetText (string text) {if (_ listbox = null) return; if (this. _ listbox. invokeRequired) // The call orientation is {if (_ listbox. items. contains (text) return; SetTextCallback d = new SetTextCallback (SetText); _ form. invoke (d, new object [] {text});} else {if (_ listbox. items. contains (text) return; this. _ listbox. items. add (text );}}}///
   /// Windows message constant ///Class CWndProMsgConst {public const int WM_DEVICECHANGE = 0x219; // system message issued by system hardware change public const int DBT_DEVICEARRIVAL = 0x8000; // The device detection is complete, 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; // uninstall the device or remove the public const int DBT_DEVICEREMOVEPENDING = 0x8003; public const int DBT_DEVICETYPEHANGED = 0x0007; public const int DBT_QUERYCHANGSPECIFIC = 0x8005; public const int DBT_DEVNODES_CECONFIG = 0x0017; public const int DBT_USERDEFINED = 0 xFFFF ;}}
  
 

Test form (rewrite message function ):

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;namespace USBMonitor{    public partial class Main : Form    {        public Main()        {            InitializeComponent();        }        CUSBMonitor usbMonitor = new CUSBMonitor();        protected override void WndProc(ref Message m)        {            usbMonitor.FillData(this, m, _listBox);            base.WndProc(ref m);        }    }}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.