【发布时间】:2008-11-07 04:24:05
【问题描述】:
我只关心 Windows,所以没有必要深究 Mono 兼容性或类似的事情。
我还应该补充一点,我正在编写的应用程序是 WPF,如果可能的话,我宁愿避免依赖 System.Windows.Forms。
【问题讨论】:
-
我们是在谈论 USB 端口吗?
-
USB 驱动器是可移动磁盘的一个示例,但 Windows 在处理事件时通常将它们视为光驱等。
我只关心 Windows,所以没有必要深究 Mono 兼容性或类似的事情。
我还应该补充一点,我正在编写的应用程序是 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");
}
}
}
【讨论】:
执行此操作的方法比使用 WMI 轮询要简单得多 - 只需捕获 WM_DEVICECHANGE:
【讨论】:
最简单的方法是创建一个自动播放处理程序:
http://www.codeproject.com/KB/system/AutoplayDemo.aspx
自动播放版本 2 是 将首先扫描的 Windows XP 四个级别的可移动媒体,当 它到了,正在寻找媒体内容 类型(音乐、图形或视频)。 申请登记已完成 基于内容类型。当一个 可移动媒体到货,Windows XP 确定要执行的操作 评估内容和比较 它向注册的处理程序 内容。
【讨论】: