Deteksi USB Drive (In/Out) menggunakan C#

seperti pada judul tulisan, kali ini saya mau bagi code C# untuk mendeteksi usb drive ketika dicolok dan dicabut….

teknik yang digunakan adalah mengoveride WindowProc (Window Procedure). contoh coding dibawah, jika dicolok nanti keluar pesan “usb masuk –> ?:\” dan ketika dicabut “usb keluar –> ?:\“. 

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace USB_Detection
{
    public partial class MainForm : Form
	{
		public MainForm()
		{
			InitializeComponent();
		}
		
		// Win32 constants
		private const int WM_DEVICECHANGE = 0x0219; //device change event
	    private const int DBT_DEVICEARRIVAL = 0x8000; //system mendeteksi device baru
	    private const int DBT_DEVICEREMOVALCOMPLETE = 0x8004; //usb dicabut
	    private const int DBT_DEVTYPVOLUME = 0x00000002; //drive type is logical volume
		
		protected override void WndProc(ref Message m)
	    {
	        if (m.Msg == WM_DEVICECHANGE)
	        {
	            if (m.WParam.ToInt32() == DBT_DEVICEARRIVAL)
	            {
		        	DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
		            if (vol.dbcv_devicetype == DBT_DEVTYPVOLUME)
		            {
		                string usb = DriveMaskToLetter(vol.dbcv_unitmask).ToString() + ":\\";
						MessageBox.Show("usb masuk --> " + usb);
		            }
	            }
	            if (m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE)
	            {
	            	DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
		            if (vol.dbcv_devicetype == DBT_DEVTYPVOLUME)
		            {
		                string usb = DriveMaskToLetter(vol.dbcv_unitmask).ToString() + ":\\";
						MessageBox.Show("usb keluar --> " + usb);
		            }
	            }
	        }
	        base.WndProc(ref m);
	    }

	    [StructLayout(LayoutKind.Sequential)]
        public struct DEV_BROADCAST_VOLUME
        {
            public int dbcv_size;
            public int dbcv_devicetype;
            public int dbcv_reserved;
            public int dbcv_unitmask;
        }

	    private static char DriveMaskToLetter(int mask)
	    {
	        char letter;
	        string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
	        int cnt = 0;
	        int pom = mask / 2;
	        while (pom != 0)    // while there is any bit set in the mask shift it right        
	        {        
	            pom = pom / 2;
	            cnt++;
	        }
	        if (cnt < drives.Length)
	            letter = drives[cnt];
	        else
	            letter = '?';
	        return letter;
	    }
	}
}

code diambil dari project ini : Detecting-USB-Drive-Removal-in-a-C-Program

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *