Detecting Usb Drive Insertion and Removal Using Windows Service and C#

Detecting USB drive insertion and removal using windows service and c#

You can use WMI, it is easy and it works a lot better than WndProc solution with services.

Here is a simple example:

using System.Management;

ManagementEventWatcher watcher = new ManagementEventWatcher();
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Query = query;
watcher.Start();
watcher.WaitForNextEvent();

detecting usb-device insertion and removal in c#

This is because GUI elements are in GUI thread of your app and you are trying to access them from the BackGroundWorker thread. You must use Delegates for working with GUI elements from your BackgroundWorker. For example:

    GUIobject.Dispatcher.BeginInvoke(
(Action)(() => { string value = myTextBox.Text; }));

On RunWorkerCompleted you are still trying to access GUI elements from the BackGroundWorker.

Detecting USB drive insertion and removal using windows service and Vb.Net

I found the solution :)

Ref.

Win32_VolumeChangeEvent class

  • Configuration Changed (1)
  • Device Arrival (2)
  • Device Removal (3)
  • Docking (4)

Code:

Imports System.Management
Imports Microsoft.Win32

Public Class Form1
Dim WithEvents pluggedInWatcher As ManagementEventWatcher
Dim WithEvents pluggedOutWatcher As ManagementEventWatcher
Dim pluggedInQuery As WqlEventQuery
Dim pluggedOutQuery As WqlEventQuery

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
pluggedInQuery = New WqlEventQuery
pluggedInQuery.QueryString = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2"
pluggedInWatcher = New ManagementEventWatcher(pluggedInQuery)
pluggedInWatcher.Start()

pluggedOutQuery = New WqlEventQuery
pluggedOutQuery.QueryString = "SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 3"
pluggedOutWatcher = New ManagementEventWatcher(pluggedOutQuery)
pluggedOutWatcher.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Private Sub pluggedInWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles pluggedInWatcher.EventArrived
MsgBox("Plugged In")
End Sub

Private Sub pluggedOutWatcher_EventArrived(sender As Object, e As EventArrivedEventArgs) Handles pluggedOutWatcher.EventArrived
MsgBox("Plugged Out")
End Sub
End Class

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

  • The DriveInfo class (msdn documentation)
  • The DriveType enumeration (msdn documentation)

Cannot implement USB Detection in .NET Framework using WMI API

Rather than regularly scanning devices you can use a WMI Events to be notified when there is a hardware change.

Starting a listener for plug & play events:

var wmiPath = new ManagementPath(@"root\cimv2");
var scope = new ManagementScope(wmiPath);
scope.Connect();
var instanceQuery = new WqlEventQuery("__InstanceOperationEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_PnPEntity\"");
wmiWatcher = new ManagementEventWatcher(scope, instanceQuery);
wmiWatcher.EventArrived += OnInstanceEvent;
wmiWatcher.Start();

The event handler:

private void OnInstanceEvent(object sender, EventArrivedEventArgs ea) {
var eventType = (string)ea.NewEvent["__CLASS"];
var targetWmiObj = ea.NewEvent["TargetInstance"] as ManagementBaseObject;
var deviceId = (string)targetWmiObj["deviceId"];

if (String.Equals("__InstanceCreationEvent", (string)ea.NewEvent["__CLASS"], StringComparison.Ordinal)) {
if (/* Filter on the device id for what is interesting here*/) {
// Handle relevant device arriving
}
}
}

There are other values of NewEvent["__CLASS"] for other event types (including device removal).

PS. This is (partial) code from a WinForms app that monitored for a specialised device being plagged in and then downloaded/uploaded data from it. All the work was done in the thread pool: everything here should just work under WPF.

Detect a USB drive being inserted - Windows Service

Windows 7 supports "trigger started services". If you want to start your service, go around in a sleeping loop, and react whenever something is plugged in, I think you would be better off (assuming Windows 7 is an option) going with a trigger started service where the OS starts the service when a USB device is plugged in. (There are other triggers but you mentioned this one.)

The sample application XP2Win7 (http://code.msdn.microsoft.com/XP2Win7) includes this functionality. It comes with full source code. Most is in VB and C# but the trigger started services part is in (native) C++.

Looking for C# code for detecting removable drive (usb flash)

There's a class called DriveDetector over at Codeproject that sounds like it does what you want.



Related Topics



Leave a reply



Submit