Community discussion forum

Is it possible to detect an usb device when the device is plugged in??

Tags:
  • 4 months ago

    I have used the following code to detect usb insertion.

    private void CreateUSBEventHandler()
    {
    WqlEventQuery q;
    ManagementOperationObserver observer = new ManagementOperationObserver();
    // Bind to local machine
    ManagementScope scope = new ManagementScope("root\\CIMV2");
    scope.Options.EnablePrivileges =
    true; //sets required privilege
    try
    {
     q =
    new WqlEventQuery();
    q.EventClassName =
    "__InstanceCreationEvent";
    q.WithinInterval =
    new TimeSpan(0, 0, 3);
    q.Condition =
    @"TargetInstance ISA 'Win32_USBControllerDevice'";
    Console.WriteLine(q.QueryString);
    m_ManagementEventWatcher =
    new ManagementEventWatcher(scope, q);
    m_ManagementEventWatcher.EventArrived +=
    new EventArrivedEventHandler(this.UsbCreationEventArrived);
    m_ManagementEventWatcher.Start();
    }

    catch (Exception ex)

    {

    Console.WriteLine(ex.Message);

    DestroyUSBEventHandler();

    }

     

  • Advertisement

    Simply the fastest line-level profiler for .NET ever

    “The low overhead means it has minimal impact on the execution of my program”
    Mark Everest, Development Team Leader, Renault F1 Team Ltd.

    Try out the new ANTS Profiler 4 for yourself. Download your 14-day trial now

  • 4 months ago

    I have used the following code to detect usb insertion.

    private void CreateUSBEventHandler()
    {
    WqlEventQuery q;
    ManagementOperationObserver observer = new ManagementOperationObserver();
    // Bind to local machine
    ManagementScope scope = new ManagementScope("root\\CIMV2");
    scope.Options.EnablePrivileges =
    true; //sets required privilege
    try
    {
     q =
    new WqlEventQuery();
    q.EventClassName =
    "__InstanceCreationEvent";
    q.WithinInterval =
    new TimeSpan(0, 0, 3);
    q.Condition =
    @"TargetInstance ISA 'Win32_USBControllerDevice'";
    Console.WriteLine(q.QueryString);
    m_ManagementEventWatcher =
    new ManagementEventWatcher(scope, q);
    m_ManagementEventWatcher.EventArrived +=
    new EventArrivedEventHandler(this.UsbCreationEventArrived);
    m_ManagementEventWatcher.Start();
    }

    catch (Exception ex)

    {

    Console.WriteLine(ex.Message);

    DestroyUSBEventHandler();

    }

     

  • 4 months ago

    The problem is that I insert one device and my handler gets called four times. Why would that be? Is there a way to determine what kind of device or manufacturer of device was plugged in? I am only looking to monitor certain devices.

Post a reply

Enter your message below

Sign in or Join us (it's free).