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

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

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13508정성태1/3/20242141오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242820닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232390닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232938닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232519닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232382Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232482닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232295개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232360디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233046닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232448오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232431Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232400Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232532Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232626닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232311개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232258Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232384개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232165개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232095오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232401개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232214개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232095오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232171개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232313닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232903닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...