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
Creating a Copy of an Object in C#
How to Elevate Privileges Only When Required
The Name 'Controlname' Does Not Exist in the Current Context
Parallel.Foreach and Async-Await
How to Check the .Net Framework Version
Fire and Forget Async Method in ASP.NET MVC
Where Is the Application.Doevents() in Wpf
Add New Item in Existing Array in C#.Net
How to Change Menu Hover Color
C# Linq Group by on Multiple Columns
Is the C# Static Constructor Thread Safe
Quickest Way to Compare Two Generic Lists for Differences
Combobox: Adding Text and Value to an Item (No Binding Source)
Easiest Way to Create a Cascade Dropdown in ASP.NET MVC 3 with C#
Password Protect a SQLite Db. Is It Possible
Split a String with Delimiters But Keep the Delimiters in the Result in C#