我只关心Windows,所以不需要关于Mono兼容性或类似的东西进入奥秘。如何检测何时使用C#插入可移动磁盘?
我还应该补充说,我正在编写的应用程序是WPF,如果可能的话,我宁愿避免依赖于System.Windows.Forms
。
我只关心Windows,所以不需要关于Mono兼容性或类似的东西进入奥秘。如何检测何时使用C#插入可移动磁盘?
我还应该补充说,我正在编写的应用程序是WPF,如果可能的话,我宁愿避免依赖于System.Windows.Forms
。
给这个一杆...
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");
}
}
}
最简单的方法是创建一个自动播放处理程序:
http://www.codeproject.com/KB/system/AutoplayDemo.aspx
自动播放第2版是在 Windows XP的一个功能,将扫描第一 的4种可移动媒体,当 它到达,寻找媒体内容 类型(音乐,图形或视频)。 以内容类型为基础完成应用程序的注册 。当 可移动媒体到达时,Windows XP 将确定要执行哪些操作,由 评估内容并将 与 内容的注册处理程序进行比较。
A detailed MSDN article也可用。
这很酷,但我真的只是在寻找能够在我的软件运行时运行的东西。谢谢,不过。 – 2008-11-07 04:37:26
有这样做比使用WMI查询的麻烦较少的方法 - 只要捕捉WM_DEVICECHANGE:
我们是在谈论一个USB港口? – 2008-11-07 04:26:04
USB驱动器将是可移动磁盘的一个例子,但Windows在处理事件时通常会将它们视为光驱等。 – 2008-11-07 04:38:40