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)
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232325닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232154C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232181Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232482닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232188닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232175닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232169오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232376닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232108개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232214닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232115오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232193오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232258닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232210닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232193닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232198닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232150VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232447닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232337닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232681닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232217오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232296닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232430닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232253닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...