C#能否实现监听USB口
2个回答
展开全部
原理就是,USB插上和拔出的时候,所有窗体都会接收到一个消息...
public void DeviceWatcher(Message message) {
if (message.Msg == WM_MESSAGES.WM_DEVICECHANGE) {
switch (message.WParam.ToInt32()) {
case WM_MESSAGES.DEVICE_MESSAGE.DBT_DEVICEARRIVAL:
// 新的USB设备
break;
case WM_MESSAGES.DEVICE_MESSAGE.DBT_DEVICEREMOVECOMPLETE:
// 一个USB设备被移除
break;
}
}
}
/// <summary>
/// windows消息的常量
/// </summary>
internal class WM_MESSAGES {
/// <summary>
/// 系统硬件改变发出的系统消息
/// </summary>
public const int WM_DEVICECHANGE = 0x219;
/// <summary>
/// 设备信息
/// </summary>
public class DEVICE_MESSAGE {
/// <summary>
/// 设备检测结束,并且可以使用
/// </summary>
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_CONFIGCHANGECANCELED = 0x0019;
public const int DBT_CONFIGCHANGED = 0x0018;
public const int DBT_CUSTOMEVENT = 0x8006;
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
/// <summary>
/// 设备卸载或者拔出
/// </summary>
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVICEREMOVEPENDING = 0x8003;
public const int DBT_DEVICETYPESPECIFIC = 0x8005;
public const int DBT_DEVNODES_CHANGED = 0x0007;
public const int DBT_QUERYCHANGECONFIG = 0x0017;
public const int DBT_USERDEFINED = 0xFFFF;
}
}
public void DeviceWatcher(Message message) {
if (message.Msg == WM_MESSAGES.WM_DEVICECHANGE) {
switch (message.WParam.ToInt32()) {
case WM_MESSAGES.DEVICE_MESSAGE.DBT_DEVICEARRIVAL:
// 新的USB设备
break;
case WM_MESSAGES.DEVICE_MESSAGE.DBT_DEVICEREMOVECOMPLETE:
// 一个USB设备被移除
break;
}
}
}
/// <summary>
/// windows消息的常量
/// </summary>
internal class WM_MESSAGES {
/// <summary>
/// 系统硬件改变发出的系统消息
/// </summary>
public const int WM_DEVICECHANGE = 0x219;
/// <summary>
/// 设备信息
/// </summary>
public class DEVICE_MESSAGE {
/// <summary>
/// 设备检测结束,并且可以使用
/// </summary>
public const int DBT_DEVICEARRIVAL = 0x8000;
public const int DBT_CONFIGCHANGECANCELED = 0x0019;
public const int DBT_CONFIGCHANGED = 0x0018;
public const int DBT_CUSTOMEVENT = 0x8006;
public const int DBT_DEVICEQUERYREMOVE = 0x8001;
public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
/// <summary>
/// 设备卸载或者拔出
/// </summary>
public const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
public const int DBT_DEVICEREMOVEPENDING = 0x8003;
public const int DBT_DEVICETYPESPECIFIC = 0x8005;
public const int DBT_DEVNODES_CHANGED = 0x0007;
public const int DBT_QUERYCHANGECONFIG = 0x0017;
public const int DBT_USERDEFINED = 0xFFFF;
}
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询