我正在编写一个使用微软知识库 823732暂时阻止用户插入新的 USB 存储设备。此方法可行,HKLM\...\Services\UsbStor
注册表项成功阻止访问新连接的设备。
是否有 WMI 事件可以告诉我驱动器连接的,无论它是否被安装?
我尝试查询__InstanceCreationEvent
但显然只有在驱动器安装并可用后才会引发此问题,这不符合我的要求。
答案1
来源:dotnetslackers.com/community/blogs/basharkokash/archive/2008/03/15/USB-Detection-source-code.aspx
相关章节:
static void AddInsetUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceCreationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += new EventArrivedEventHandler(USBAdded);
w.Start();
}
catch (Exception e)
{
Console.WriteLine (e.Message);
if (w != null)
w.Stop();
}
}