我是C#的新手 - 三天前开始,因为有关USB驱动器的特殊需求。在这里和那里阅读我可以有以下代码工作。我想要的是知道用户何时在USB端口插入pendrive。C# - 在Windows XP上未检测到事件--USB驱动器
唯一的问题是在XP32(我测试的唯一的XP)事件将永远不会被检测到。在Windows 7上它运行完美。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Diagnostics;
using System.Threading;
using System.IO;
using Microsoft.Win32;
using System.Security.Permissions;
namespace X
{
class Program
{
static void Main(string[] args)
{
ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
watcher.Query = query;
watcher.Start();
watcher.WaitForNextEvent();
// DO something if a pen drive (or any storage device) is inserted.
// Works fine on Windows 7
// XP will ignore the event...
}
}
}
任何建议将非常欢迎!
问候,
塞尔吉奥
这可能适合你:http://blogs.technet.com/b/heyscriptingguy/archive/2006/02/13/how-can-i-determine-when-a-removable-drive-gets-connected .aspx – gaynorvader
看看这个链接它可能是一个更好的选择,你在做什么.. http://www.codeproject.com/Articles/3946/Trapping-windows-messages – MethodMan
WqlEventQuery不支持Windows XP。所以这个方法不能使用。更详细地研究以前的版本DID支持Windows XP。你使用的是什么版本的.NET Framework?这意味着这不起作用的原因实际上是因为'Win32_VolumeChangeEvent'不支持Windows XP。这也是不正确的基于http://msdn.microsoft.com/en-us/library/windows/desktop/aa394516(v=vs.85).aspx –