Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - USB 장치의 연결 및 해제 알림을 위한 WM_DEVICECHANGE 메시지 처리

다음과 같은 질문이 있군요. ^^

MFC 에서 WM_DEVICECHANGE 메시지의 Wparam이 항상 7로 들어옵니다.
; https://social.msdn.microsoft.com/Forums/ko-KR/bd667c77-428b-439f-9cf0-9229de544b65/mfc-wmdevicechange-wparam-7-?forum=visualcplusko

편하게 C# WinForm으로 구현해 보겠습니다. 우선, 기본 상태에서 WM_DEVICECHANGE의 상태 알림을 확인해 보면,

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        const int WM_DEVICECHANGE = 0x0219;

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_DEVICECHANGE)
            {
                Debug.WriteLine(DateTime.Now + ": " + m.Msg + ", " + m.WParam.ToInt64() + ", " + m.LParam.ToInt64());
            }

            base.WndProc(ref m);
        }
    }
}

USB 장치를 연결 및 해제 시 다음과 같은 결과를 얻을 수 있습니다.

[연결 시]
2018-12-05 오전 8:52:35: 537, 7, 0
2018-12-05 오전 8:52:36: 537, 7, 0
2018-12-05 오전 8:52:36: 537, 7, 0

[해제 시]
2018-12-05 오전 8:52:43: 537, 7, 0
2018-12-05 오전 8:52:43: 537, 7, 0

보는 바와 같이, 연결과 해제에 따른 WPARAM의 값이 7로 동일하기 때문에 구분을 할 수 있는 기준이 없습니다. 이제 문서에 따라,

RegisterDeviceNotification function
; https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-registerdevicenotificationa

RegisterDeviceNotification을 처리해 줄 UsbAlarm이라는 타입을 다음과 같이 만들고,

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    public class UsbAlarm : IDisposable
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr RegisterDeviceNotification(IntPtr hRecipient, IntPtr NotificationFilter, uint Flags);

        [DllImport("user32.dll", SetLastError = true)]
        static extern bool UnregisterDeviceNotification(IntPtr Handle);

        List<IntPtr> _notifications = new List<IntPtr>();

        public const int WM_DEVICECHANGE = 0x0219;
        public const int DBT_DEVTYP_DEVICEINTERFACE = 0x05;
        public const int DEVICE_NOTIFY_WINDOW_HANDLE = 0x00000000;

        // 연결된 장치 알아내기
        // http://bboogugu.egloos.com/v/591770
        Guid[] GUID_DEVINTERFACE_LIST =
        {
            // GUID_DEVINTERFACE_USB_DEVICE
            new Guid(0xA5DCBF10, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED),
            // GUID_DEVINTERFACE_COMPORT
            new Guid(0x86e0d1e0, 0x8089, 0x11d0, 0x9c, 0xe4, 0x08, 0x00, 0x3e, 0x30, 0x1f, 0x73),
            // GUID_DEVINTERFACE_MODEM
            new Guid(0x2c7089aa, 0x2e0e, 0x11d1, 0xb1, 0x14, 0x00, 0xc0, 0x4f, 0xc2, 0xaa, 0xe4),
            // GUID_DEVINTERFACE_DISK
            new Guid(0x53f56307, 0xb6bf, 0x11d0, 0x94, 0xf2, 0x00, 0xa0, 0xc9, 0x1e, 0xfb, 0x8b),
            // GUID_DEVINTERFACE_HID, 
            new Guid(0x4D1E55B2, 0xF16F, 0x11CF, 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30),
            // GUID_NDIS_LAN_CLASS
            new Guid(0xad498944, 0x762f, 0x11d0, 0x8d, 0xcb, 0x00, 0xc0, 0x4f, 0xc3, 0x35, 0x8c),
            // GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR
            new Guid(0x4D36E978, 0xE325, 0x11CE, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18),
            // GUID_DEVINTERFACE_PARALLEL
            new Guid(0x97F76EF0, 0xF883, 0x11D0, 0xAF, 0x1F, 0x00, 0x00, 0xF8, 0x00, 0x84, 0x5C),
            // GUID_DEVINTERFACE_PARCLASS
            new Guid(0x811FC6A5, 0xF728, 0x11D0, 0xA5, 0x37, 0x00, 0x00, 0xF8, 0x75, 0x3E, 0xD1)
        };

        unsafe public UsbAlarm(IntPtr windowHandle)
        {
            DEV_BROADCAST_DEVICEINTERFACE filter = new DEV_BROADCAST_DEVICEINTERFACE();
            filter.dbcc_size = DEV_BROADCAST_DEVICEINTERFACE.Size;
            filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;

            foreach (Guid guid in GUID_DEVINTERFACE_LIST)
            {
                filter.dbcc_classguid = guid;

                DEV_BROADCAST_DEVICEINTERFACE* ptr = &filter;
                IntPtr ptrStruct = new IntPtr(ptr);
                IntPtr hDevNotify = RegisterDeviceNotification(windowHandle, ptrStruct, DEVICE_NOTIFY_WINDOW_HANDLE);
                if (hDevNotify == IntPtr.Zero)
                {
                    Debug.WriteLine("Failed to register: " + guid);
                }
                else
                {
                    _notifications.Add(hDevNotify);
                }
            }
        }

        public void Dispose()
        {
            foreach (IntPtr handle in _notifications)
            {
                UnregisterDeviceNotification(handle);
            }
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct DEV_BROADCAST_DEVICEINTERFACE
    {
        public int dbcc_size;
        public int dbcc_devicetype;
        public int dbcc_reserved;
        public Guid dbcc_classguid;
        public char dbcc_name;
        public static readonly int Size = Marshal.SizeOf(typeof(DEV_BROADCAST_DEVICEINTERFACE));
    }
}

이렇게 Form에서 사용해 봅니다.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        UsbAlarm _usbAlarm;

        public Form1()
        {
            InitializeComponent();
            _usbAlarm = new UsbAlarm(this.Handle);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (_usbAlarm != null)
            {
                _usbAlarm.Dispose();
            }

            base.OnClosing(e);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == UsbAlarm.WM_DEVICECHANGE)
            {
                Debug.WriteLine("Form1: " + DateTime.Now + ": " + m.Msg + ", " + m.WParam.ToInt64() + ", " + m.LParam.ToInt64());
            }

            base.WndProc(ref m);
        }
    }
}

다시 USB 장치를 연결 및 해제하면 이제 그 상태를 WPARAM 값을 통해 구분할 수 있습니다.

[연결 시]
Form1: 2018-12-05 오전 9:08:37: 537, 32768, 5892240
Form1: 2018-12-05 오전 9:08:37: 537, 32768, 5892240

DBT_DEVICEARRIVAL (0x8000 == 32768)

[해제 시]
Form1: 2018-12-05 오전 9:08:44: 537, 32772, 5892240
Form1: 2018-12-05 오전 9:08:44: 537, 32772, 5892240

DBT_DEVICEREMOVECOMPLETE (0x8004 == 32772)

잘 동작하는군요. ^^




다시 질문으로 돌아가서, 검색 결과 다이얼로그의 최상위에서만 정상 결과가 들어온다는 이야기를 하고 있습니다. 이게 좀 이상합니다. RegisterDeviceNotification의 첫 번째 인자가 윈도우 핸들 값인데, 윈도우 시스템이 굳이 저 윈도우 핸들의 부모 핸들을 탐색한 후 최상위 윈도우에만 알림을 전달할 것 같지는 않습니다.

실제로 테스트를 해볼까요? ^^

MainForm에 버튼을 추가하고 그에 대해 MyForm 하위 대화창을 띄워두도록 한 후,

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == UsbAlarm.WM_DEVICECHANGE)
            {
                Debug.WriteLine("Form1: " + DateTime.Now + ": " + m.Msg + ", " + m.WParam.ToInt64() + ", " + m.LParam.ToInt64());
            }

            base.WndProc(ref m);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyForm form = new MyForm();
            form.ShowDialog();
        }
    }
}

MyForm 코드에 UsbAlarm 코드를 구현하면,

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class MyForm : Form
    {
        UsbAlarm _usbAlarm;

        public MyForm()
        {
            InitializeComponent();
            _usbAlarm = new UsbAlarm(this.Handle);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == UsbAlarm.WM_DEVICECHANGE)
            {
                Debug.WriteLine("MyForm: " + DateTime.Now + ": " + m.Msg + ", " + m.WParam.ToInt64() + ", " + m.LParam.ToInt64());
            }

            base.WndProc(ref m);
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (_usbAlarm != null)
            {
                _usbAlarm.Dispose();
            }

            base.OnClosing(e);
        }
    }
}

USB 연결/해제 시 다음과 같은 알림을 받을 수 있습니다.

[연결 시]
MyForm: 2018-12-05 오전 9:20:58: 537, 7, 0
Form1: 2018-12-05 오전 9:20:58: 537, 7, 0
MyForm: 2018-12-05 오전 9:20:58: 537, 32768, 7331776
MyForm: 2018-12-05 오전 9:20:58: 537, 32768, 7331776

[해제 시]
MyForm: 2018-12-05 오전 9:21:05: 537, 32772, 7331776
MyForm: 2018-12-05 오전 9:21:05: 537, 32772, 7331776
MyForm: 2018-12-05 오전 9:21:16: 537, 7, 0
Form1: 2018-12-05 오전 9:21:16: 537, 7, 0

정상적으로 Top-level 윈도우가 아니라 RegisterDeviceNotification에 전달한 윈도우로 이벤트가 잘 전달이 되는 것을 확인할 수 있습니다. 그런데, 왜 뜬금없이 Top-level 윈도우에서만 받을 수 있다는 이야기가 나왔을까요? 이쯤에서 다시 문서를 보면,

Applications send event notifications using the BroadcastSystemMessage function. Any application with a top-level window can receive basic notifications by processing the WM_DEVICECHANGE message. Applications can use the RegisterDeviceNotification function to register to receive device notifications.


의문이 풀립니다. 즉, Top-level 윈도우는 RegisterDeviceNotification으로 알림 등록을 하지 않아도 WM_DEVICECHANGE 이벤트를 기본적인 수준에서 받을 수 있다는 내용인데, 질문자가 검색한 글의 작성자는 이것을 잘못 해석한 내용을 써놓았던 것입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/22/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-11-29 04시00분
[StarRang] 안녕하세요.
WndProc 함수는 USB 포함 모든 Portable Device에 대해서 인식할 수 있는데,
모든 Portable Device가 아닌 모바일 기기나 특정 기기만 인식할 수 있도록 가능할까요?
[guest]
2022-11-29 04시12분
문서에도 나오지만 RegisterDeviceNotification의 두 번째 인자에 NotificationFilter를 전달하고 있습니다. 검색해 보면,

Obtaining Device Notification for USB Device Arrival and Surprise Removal for MFC
; https://community.silabs.com/s/article/Obtaining-Device-Notification-for-USB-Device-Arrival-and-Surprise-Removal-for-C-MFC

관련 예제 코드가 있으니 어렵지 않게 만드실 수 있을 것입니다. 저도 해보진 않아서 어느 정도의 필터링 기능을 하는지는 모릅니다. 해보시고 ^^ 후기 좀 남겨주세요.
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
12922정성태1/14/20226641개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225627개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226398오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226227Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226446Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225676오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225408오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225679오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227583VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228127.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228750개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226100VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226560제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227963오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225816.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226251오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226868.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226529오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228553개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227148.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227185오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227277오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228928개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228410개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228966.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
12897정성태1/2/20227847.NET Framework: 1128. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 [4]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...