问题
I'm looking for a C# code snippet to give me a notification for when a USB drive is plugged into my PC in Windows Vista (or win7)
回答1:
There's a class called DriveDetector over at Codeproject that sounds like it does what you want.
回答2:
Look at WM_DEVICECHANGE. This message should be sent when a drive is inserted.
回答3:
I know this is not exactly what you asked for, but if you want to check what devices are available at any moment in time, there's another way. You can use the WMI classes in the System.Management namespace, I've used this method and it works well.
If you take a look at this answer, it shows how to enumerate all the drives on the system. You can then take a look at the drive type to determine whether or not it's a USB stick.
回答4:
I wrote a powershell module that uses a System.Management.ManagementEventWatcher and the WMI class Win32_VolumeChangedEvent to surface new events that you may register for within powershell covering device removal, addition etc. You should be able to figure out the relevant plumbing from this blog post of mine:
http://www.nivot.org/nivot2/post/2008/08/16/AutoMountunmountNewPSDrivesForRemovableDrivesAndNetworkSharesInPowerShellV2.aspx
You should be able to wire up an event for new drives in less than ten lines of C# using the methods I use in the above script.
Hope this helps.
来源:https://stackoverflow.com/questions/715739/looking-for-c-sharp-code-for-detecting-removable-drive-usb-flash