使用 WMI 在 Windows 上插入 USB 设备时打开我的应用程序
我试图在有人插入 USB 设备时启动一个事件。现在,我满足于简单地将一些内容打印到控制台(在成品中,它将启动一个应用程序)。
有两个问题: 1)我需要动态地将参数传递给管理范围,因为这将安装在我不使用或我不知道其名称的计算机上。 2) 当我调用 w.Start(); 时,出现无效的命名空间异常。
有什么想法我做错了吗?
static ManagementEventWatcher w=null;
static void Main(string[] args)
{
AddInstUSBHandler();
for(;;);
}
public static void USBRemoved(object sneder, EventArgs e)
{
Console.WriteLine("A USB device inserted");
}
static void AddInstUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("HQ\\DEV1");
scope.Options.EnablePrivileges=true;
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(USBRemoved);
w.Start();
}
I'm trying to launch an event when someone plugs in a USB device. For now, I'm content to simply print something to the console (in the finished product, it will launch an application).
This code is very loosely adapted from: https://serverfault.com/questions/115496/use-wmi-to-detect-a-usb-drive-was-connected-regardless-of-whether-it-was-mounted
There are two problems:
1) I need to pass the argument to Management scope dynamically because this will be installed on computers I don't use or whose name I don't know. 2) I'm getting an invalid namespace exception when I call w.Start();
Any ideas what I'm doing wrong?
static ManagementEventWatcher w=null;
static void Main(string[] args)
{
AddInstUSBHandler();
for(;;);
}
public static void USBRemoved(object sneder, EventArgs e)
{
Console.WriteLine("A USB device inserted");
}
static void AddInstUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("HQ\\DEV1");
scope.Options.EnablePrivileges=true;
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(USBRemoved);
w.Start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行不正确 -> “HQ\DEV1”
关注 ManagementScope 类
This line is incorrect -> "HQ\DEV1"
Follow ManagementScope Class