7

I need to detect when a new drive is plugged into a Windows system through a USB port, firewire port, etc. I am aware of the WM_DEVICECHANGE message, but this requires a window to be open in order to use it. Is there a way to create a background process in C# that detects when new drives are plugged in?

Background info: I am wanting to write this app to remove a worm from company removable drives. Regular antivirus software is failing to removing it. We have a script that will remove the worm, but it must be run manually, which is not good enough to contain the outbreak.

Phil
  • 6,561
  • 4
  • 44
  • 69

4 Answers4

4

A windows service should do the trick

Try reworking the CodeProject DriveDetector as a service and you should have what you need

Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
  • 2
    Did it and it worked. For a service, I just had to make sure I created another thread with an infinite loop that kept calling Application.DoEvents(). If you don't do that, the DriveDetector will hang and fail to receive WM_DEVICECHANGE messages. Also, I had to make sure that desktop interaction is enabled for the service, since DriveDetector uses a hidden form to do its work. – Phil Nov 24 '09 at 17:54
  • 3
    Looking back at this project, I realize it's not good practice to allow desktop interaction with a service. Nowadays I recommend creating a regular executable and dropping it in the startup folder. – Phil Oct 02 '10 at 14:03
1

You will need to subscribe to RegisterDeviceNotification, and bind it to a service status handle. See also http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/9ae4478a-1133-44ba-8a1c-3e4be3856e37.

I'm not quite sure how to implement this, has been a long time ago.

Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120
0

This blogpost show how to handle system events, https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/howdoi/?p=135 maybe you can use it for the event that you want to handle

Community
  • 1
  • 1
Ivo
  • 3,406
  • 4
  • 33
  • 56
0

You may create a hidden window or run a service as it should work with a window handle or a service status handle.

Guillaume
  • 12,824
  • 3
  • 40
  • 48