1、Winform代码:
public partial class USBDeviceMode : Form
{
public USBDeviceMode()
{
InitializeComponent();
UsbNotification.RegisterUsbDeviceNotification(this.Handle);
}
private void RFIDReaderMode_Load(object sender, EventArgs e)
{
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == (int)HandleNotification_MessageMsg.DBT_DEVTYP_DEVICEINTERFACE_Msg)
{
switch ((int)m.WParam)
{
case (int)HandleNotification_MessageWParam.DBT_DEVTYP_Removecomplete:
textBox1.AppendText(@"
检测到有设备拔出");
break;
case (int)HandleNotification_MessageWParam.DBT_DEVTYP_Arrival:
textBox1.AppendText(@"
检测到有设备插入");
break;
}
}
}
}
2、UsbNotification类:
using System;
using System.Runtime.InteropServices;
using static ZhiBiXiaobai.WindowAPIHelper.WindowsAPI_DeviceManagement;
namespace WinFormsApp1
{
/// <summary>
/// 监听USB设备插拔
/// </summary>
public class UsbNotification
{
#region 常量
private static readonly Guid GuidDevinterfaceUSBDevice = new("A5DCBF10-6530-11D2-901F-00C04FB951ED"); // 用作USB设备标签
#endregion 常量
private static IntPtr notificationHandle; // 通知句柄(这里给窗口句柄)
/// <summary>
/// 指定(注册)一个窗口,以便在USB设备插入或拔出时接收通知。
/// </summary>
/// <param name="windowHandle">接收通知的窗口句柄。</param>
public static void RegisterUsbDeviceNotification(IntPtr windowHandle)
{
DEV_BROADCAST_DEVICEINTERFACE dbi = new() // 存储设备信息的对象
{
dbch_devicetype = DEV_BROADCAST_DEVICEINTERFACE_Devicetype.DBT_DEVTYP_DEVICEINTERFACE, // 通知类别为“设备的类”
dbch_reserved = 0, // 保留不使用
dbch_classguid = GuidDevinterfaceUSBDevice,
dbch_name = '0'
};
dbi.dbch_size = Marshal.SizeOf(dbi); // 从进程的非托管内存中给DevBroadcastDeviceinterface分配内存
//IntPtr buffer = Marshal.AllocHGlobal(dbi.dbch_size); // 从进程的非托管内存中给DevBroadcastDeviceinterface分配内存
//Marshal.StructureToPtr(dbi, buffer, true); // 将数据从托管对象封送到非托管内存块(dbi->buffer,删除旧的数据)
notificationHandle = RegisterDeviceNotification(windowHandle, dbi, 0);
}
/// <summary>
/// 注销USB设备通知窗口
/// </summary>
public static void UnregisterUsbDeviceNotification()
{
UnregisterDeviceNotification(notificationHandle);
}
}
}
3、WindowsAPI类:
4、HandleNotification_MessageMsg与HandleNotification_MessageWParam:
WindowsAPI-C#版_句柄回调常用通知类型汇总(HandleNotification)
5、补充-WPF写法:
标签:插拔,dbi,usb,示例,HandleNotification,static,dbch,public,WindowsAPI From: https://www.cnblogs.com/qq2806933146xiaobai/p/16899198.html