Home >Backend Development >C++ >How Can I Detect USB Drive Insertion and Removal Using a C# Windows Service?

How Can I Detect USB Drive Insertion and Removal Using a C# Windows Service?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-14 08:51:47995browse

How Can I Detect USB Drive Insertion and Removal Using a C# Windows Service?

Monitoring USB Drive Activity in a C# Windows Service

This article details how to create a C# Windows service that reliably detects USB drive insertion and removal events. This is crucial for applications designed to automatically launch upon drive connection and close when the drive is disconnected.

Implementing USB Event Detection

The most effective method for tracking these events is using Windows Management Instrumentation (WMI). WMI provides a robust interface for interacting with system resources, making it ideal for this task.

WMI-based Solution

Below is a streamlined example demonstrating WMI's application to detect USB drive insertion and removal:

<code class="language-csharp">using System.Management;

// Initialize WMI event watcher
ManagementEventWatcher watcher = new ManagementEventWatcher();

// Define the WQL query for volume change events (EventType = 2 signifies insertion/removal)
WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");

// Assign the query to the watcher
watcher.Query = query;

// Specify the event handler
watcher.EventArrived += watcher_EventArrived;

// Start monitoring
watcher.Start();

// Wait for events
watcher.WaitForNextEvent();


// Event handler to process drive insertion/removal events
private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    // Process the event data (e.NewEvent) to determine which drive was affected and whether it was inserted or removed.
    // ... your code to handle the event ...
}</code>

This code sets up a WMI event watcher to listen for Win32_VolumeChangeEvent events where EventType is 2. The watcher_EventArrived event handler is triggered when a drive is inserted or removed, allowing you to process the event details (available in e.NewEvent). You'll need to add your logic within the watcher_EventArrived method to determine the specific drive and the type of event (insertion or removal).

The above is the detailed content of How Can I Detect USB Drive Insertion and Removal Using a C# Windows Service?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn