Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 251133
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T21:34:09+00:00 2026-05-11T21:34:09+00:00

Our winforms application supports a custom controller using the manufacturer’s SDK, but there’s no

  • 0

Our winforms application supports a custom controller using the manufacturer’s SDK, but there’s no support to detect whether a device is present or not. How do I check whether a given USB device is plugged in?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T21:34:09+00:00Added an answer on May 11, 2026 at 9:34 pm

    The following class is used to monitor devices, you could use this to detect a USB device.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Management;
    
    namespace DeviceMonitor.Event
    {
        /// <summary>Media watcher delegate.</summary>
        /// <param name="sender"></param>
        /// <param name="driveStatus"></param>
        public delegate void MediaWatcherEventHandler(object sender, DeviceMonitor.Event.MediaEvent.DriveStatus driveStatus );
    
        /// <summary>Class to monitor devices.</summary>
        public class MediaEvent
        {
            #region Variables
    
            /*------------------------------------------------------------------------*/
            private string m_logicalDrive;
            private ManagementEventWatcher m_managementEventWatcher = null;
            /*------------------------------------------------------------------------*/
            #endregion
    
            #region Events
            /*------------------------------------------------------------------------*/
            public event MediaWatcherEventHandler MediaWatcher;
            /*------------------------------------------------------------------------*/
            #endregion
    
    
            #region Enums
            /*------------------------------------------------------------------------*/
            /// <summary>The drive types.</summary>
            public enum DriveType
            {
              Unknown = 0,
              NoRootDirectory = 1,
              RemoveableDisk  = 2,
              LocalDisk       = 3,
              NetworkDrive    = 4,
              CompactDisk     = 5,
              RamDisk         = 6
            }
    
            /// <summary>The drive status.</summary>
            public enum DriveStatus
            {
              Unknown  = -1,
              Ejected  = 0,
              Inserted = 1,
            }
    
           /*-----------------------------------------------------------------------*/
           #endregion
    
    
           #region Monitoring
           /*-----------------------------------------------------------------------*/
           /// <summary>Starts the monitoring of device.</summary>
           /// <param name="path"></param>
           /// <param name="mediaEvent"></param>
           public void Monitor( string path, MediaEvent mediaEvent ) 
           {
               if( null == mediaEvent ) 
               {
                  throw new ArgumentException( "Media event cannot be null!" );
               }
    
               //In case same class was called make sure only one instance is running
               /////////////////////////////////////////////////////////////
               this.Exit();
    
               //Keep logica drive to check
               /////////////////////////////////////////////////////////////
               this.m_logicalDrive = this.GetLogicalDrive( path );
    
               WqlEventQuery wql;
               ManagementOperationObserver observer = new ManagementOperationObserver();
    
               //Bind to local machine
               /////////////////////////////////////////////////////////////
               ConnectionOptions opt = new ConnectionOptions();
    
               //Sets required privilege
               /////////////////////////////////////////////////////////////
               opt.EnablePrivileges = true;
               ManagementScope scope = new ManagementScope( "root\\CIMV2", opt );
    
               try 
               {
                  wql = new WqlEventQuery();
                  wql.EventClassName = "__InstanceModificationEvent";
                  wql.WithinInterval = new TimeSpan( 0, 0, 1 );
    
                  wql.Condition = String.Format( @"TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DeviceId = '{0}'", this.m_logicalDrive );
                  this.m_managementEventWatcher = new ManagementEventWatcher( scope, wql );
    
                  //Register async. event handler
                  /////////////////////////////////////////////////////////////
                  this.m_managementEventWatcher.EventArrived += new EventArrivedEventHandler( mediaEvent.MediaEventArrived );
                  this.m_managementEventWatcher.Start();
               } 
               catch( Exception e ) 
               {
                  this.Exit();
                  throw new Exception( "Media Check: "  + e.Message );
               }
           }
    
           /// <summary>Stops the monitoring of device.</summary>
           public void Exit( ) 
           {
                 //In case same class was called make sure only one instance is running
                 /////////////////////////////////////////////////////////////
                 if( null != this.m_managementEventWatcher ) 
                 {
                      try 
                      {
                           this.m_managementEventWatcher.Stop();
                           this.m_managementEventWatcher = null;
                      } 
                      catch {}
                 }
            }
            /*-----------------------------------------------------------------------*/
            #endregion
    
    
            #region Helpers
            /*-----------------------------------------------------------------------*/
    
            private DriveStatus m_driveStatus = DriveStatus.Unknown;
    
            /// <summary>Triggers the event when change on device occured.</summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void MediaEventArrived( object sender, EventArrivedEventArgs e ) 
            {
    
                // Get the Event object and display it
                PropertyData pd = e.NewEvent.Properties["TargetInstance"];
                DriveStatus driveStatus = this.m_driveStatus;
    
                if( pd != null ) 
                {
                    ManagementBaseObject mbo = pd.Value as ManagementBaseObject;
                    System.IO.DriveInfo info = new System.IO.DriveInfo( (string)mbo.Properties["DeviceID"].Value );
                    driveStatus = info.IsReady ? DriveStatus.Inserted : DriveStatus.Ejected;
                }
    
                if( driveStatus != this.m_driveStatus )
                {
                    this.m_driveStatus = driveStatus;
                    if( null != MediaWatcher ) 
                    {
                        MediaWatcher( sender, driveStatus );
                    }
                }
            }
    
    
            /// <summary>Gets the logical drive of a given path.</summary>
            /// <param name="path"></param>
            /// <returns></returns>
            private string GetLogicalDrive( string path ) 
            {
                System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo( path );
                string root = dirInfo.Root.FullName;
                string logicalDrive = root.Remove(root.IndexOf(System.IO.Path.DirectorySeparatorChar ) );
                return logicalDrive;
            }
            /*-----------------------------------------------------------------------*/
            #endregion
        }
    }
    

    Edit

    Extracted from http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/09912cee-4d2d-4efd-82a0-da20024b868b

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 123k
  • Answers 124k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I guess you can kill your grandchildren with this code… May 12, 2026 at 1:12 am
  • Editorial Team
    Editorial Team added an answer Perhaps: <servlet> <servlet-name>HelloExcel</servlet-name> <servlet-class>writeDataBase.readDataBase</servlet-class> </servlet> <servlet> <servlet-name>HelloWord</servlet-name> <servlet-class>writeDataBase.writeDataBase</servlet-class> </servlet> <servlet-mapping>… May 12, 2026 at 1:12 am
  • Editorial Team
    Editorial Team added an answer I figured out this issue. I used IJavaElement instead of… May 12, 2026 at 1:12 am

Related Questions

Our winforms application supports a custom controller using the manufacturer's SDK, but there's no
I currently have a functioning in-house Windows Forms application which extensively uses the DataGridView
Our WinForms application has been reported to occasionally just close on its own. It
So I have a nasty stack overflow I have been trying to track down
We are developing a Winforms application and in the process of optimizing the start-up

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.