C#

[C#]USB 장치 인식 예제

선영아 사랑해 2016. 2. 23. 15:31

컴퓨터에 USB 장치가 추가 또는 해제됐을 경우 확인 할 수 있는 코드입니다.


protected override void WndProc(ref Message m)
{
    UInt32 WM_DEVICECHANGE = 0x0219;
    UInt32 DBT_DEVTUP_VOLUME = 0x02;                      //저장 장치

    UInt32 DBT_DEVTYP_PORT = 0x03;                           //포트 장치
    UInt32 DBT_DEVICEARRIVAL = 0x8000;
    UInt32 DBT_DEVICEREMOVECOMPLETE = 0x8004;

    if ((m.Msg == WM_DEVICECHANGE) && (m.WParam.ToInt32() == DBT_DEVICEARRIVAL))//디바이스 연결
    {
        int devType = System.Runtime.InteropServices.Marshal.ReadInt32(m.LParam, 4);

        if (devType == DBT_DEVTUP_VOLUME)
        {
                MessageBox.Show("저장장치 연결");
        }
    }

    if((m.Msg == WM_DEVICECHANGE) &&(m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE))  //디바이스 연결 해제
    {
        int devType = System.Runtime.InteropServices.Marshal.ReadInt32(m.LParam, 4);
       
        if (devType == DBT_DEVTUP_VOLUME)
        {
            MessageBox.Show("저장장치 연결해제");
        }

        else if(devType == DBT_DEVTYP_PORT)

        {

            string portName = System.Runtime.InteropServices.Marshal.PtrToStringAuto((IntPtr)((long)m.LParam + 12));     //연결해제된 PORT NAME

            //ex.) USB To Serial 장비 등등

MessageBox.Show("PORT장치 연결해제");

         }
    }

    base.WndProc(ref m);
}