본문 바로가기
개발언어/C#

[C#] USB상태 변경시

by 창용이랑 2023. 5. 10.
728x90

..

 

private const int DBT_DEVICEARRIVAL = 0x8000;
private const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
private const int DBT_DEVTYP_VOLUME = 0x00000002;

using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace UsbDriveDetector
{
   public partial class Form1 : Form
   {
      private const int WM_DEVICECHANGE = 0x219;
      private const int DBT_DEVICEARRIVAL = 0x8000;
      private const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
      private const int DBT_DEVTYP_VOLUME = 0x00000002;

      public Form1()
      {
         InitializeComponent();
      }

      protected override void WndProc(ref Message m)
      {
         base.WndProc(ref m);

         switch(m.Msg)
         {
            case WM_DEVICECHANGE:
               switch((int)m.WParam)
               {
                  case DBT_DEVICEARRIVAL:
                     listBox1.Items.Add("New Device Arrived");

                     int devType = Marshal.ReadInt32(m.LParam, 4);
                     if(devType == DBT_DEVTYP_VOLUME)
                     {
                        DevBroadcastVolume vol;
                        vol = (DevBroadcastVolume)
                           Marshal.PtrToStructure(m.LParam,
                           typeof (DevBroadcastVolume));
                        listBox1.Items.Add("Mask is " + vol.Mask);
                     }

                  break;

               case DBT_DEVICEREMOVECOMPLETE:
                  listBox1.Items.Add("Device Removed");
                  break;

            }
            break;
         }

      }
   }
}