我是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 –