admin管理员组文章数量:1639833
首先,定义USB相关驱动的消息常量,如下,其中WM_DEVICECHANGE表示有设备发生变化,对USB插入和拔出事件来说,只有只需要定义两个:DBT_DEVICEARRIVAL(插入设备)和DBT_DEVICEREMOVECOMPLETE(拔出设备)。所有的消息常量如下:
public const int WM_DEVICECHANGE = 0x219;
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;
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;
定义好消息常量之后,需要重写WndProc,如下:
protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == WM_DEVICECHANGE)
{
switch (m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
//USB插入时要处理的事件
break;
case DBT_DEVICEREMOVECOMPLETE:
//USB拔出时要处理的事件
break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
base.WndProc(ref m);
}
重写代码时只列出了USB插入和拔出时处理方法,如果想添加其他的可以依照这两个添加。
如果想获取插入可移动设备的盘符,可以用以下代码:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
Text = "盘符:" + drive.Name.ToString();
break;
}
}
本文标签:
版权声明:本文标题:C#学习——识别U盘 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729288720a1194216.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论