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

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-14 06:24:43410browse

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

C# and Windows Services: Monitoring USB Drive Connections

Automating application startup and shutdown based on USB drive insertion and removal is valuable for distributed systems. This article explores efficient methods for achieving this functionality within a C# Windows Service.

C# Implementation Strategies

A robust solution utilizes Windows Management Instrumentation (WMI), a powerful tool for system monitoring and event management. WMI allows querying for events related to device changes. A concise C# WMI example:

<code class="language-csharp">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();</code>

The EventArrived event handler is triggered on USB insertion or removal, providing details about the event and the affected drive. This WMI approach is significantly more reliable than using WndProc within a service context.

The above is the detailed content of How Can I Detect USB Drive Insertion and Removal in 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