如何检测时,使用C#插入移动硬盘? [英] How do I detect when a removable disk is inserted using C#?
本文介绍了如何检测时,使用C#插入移动硬盘?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是担心Windows系统,因此没有必要进入有关单声道兼容性或任何类似的秘籍。
I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that.
我还要补充一点,我正在写的应用程序是WPF,和我preFER避免服用对 System.Windows.Forms的依赖
如果在所有可能的。
I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on System.Windows.Forms
if at all possible.
推荐答案
给这个一杆...
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
namespace WMITestConsolApplication
{
class Program
{
static void Main(string[] args)
{
AddInsertUSBHandler();
AddRemoveUSBHandler();
while (true) {
}
}
static ManagementEventWatcher w = null;
static void AddRemoveUSBHandler()
{
WqlEventQuery q;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;
try {
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = "TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);
w.EventArrived += USBRemoved;
w.Start();
}
catch (Exception e) {
Console.WriteLine(e.Message);
if (w != null)
{
w.Stop();
}
}
}
static void AddInsertUSBHandler()
{
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 += USBInserted;
w.Start();
}
catch (Exception e) {
Console.WriteLine(e.Message);
if (w != null)
{
w.Stop();
}
}
}
static void USBInserted(object sender, EventArgs e)
{
Console.WriteLine("A USB device inserted");
}
static void USBRemoved(object sender, EventArgs e)
{
Console.WriteLine("A USB device removed");
}
}
}
这篇关于如何检测时,使用C#插入移动硬盘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文