Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

USB NOTIFICATION

Posted on 2011-03-09
3
658 Views
Last Modified: 2012-05-11
hi -- i'm using C#, VS2010, and .net 4.0. i've written an application that interfaces to a custom usb device (using a bulk protocol driver). it works fine if the device is plugged in before i open the application (i initialize theusb device protocol when i open the appication). what i would like to do is be able to plug in the device after the application is open. to do that, i would need to use an event with a delegate attached that would call the initialization. what i'm looking for is what event should i be posting for?
I use P/invoke to call the various methods in the usb device handler that was supplied to me as part of the device. i have access to the C code for the device handler. as near as i can tell, the device handler just wraps win32usb calls.
thanks,
0
Comment
Question by:jdcoburn
  • 2
3 Comments
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 35090419
I would use a WMI event watcher to detect an instance creation for a Win32_USBControllerDevice.

USB Port Insert / Remove detection using WMI
http://dotnetslackers.com/community/blogs/basharkokash/archive/2008/02/06/usb-port-insert-remove-detection-using-wmi.aspx


using System;
using System.IO;
using System.Management;
using System.Windows.Forms;

public partial class Form1 : Form
{
    // Used to subscribe to event notifications based on a specified event query.
    private ManagementEventWatcher _watcher = null;

    private StreamWriter _writer;

    private void Form1_Load(object sender, EventArgs e)
    {
        this.AddUSBHandler();
    }

    private void AddUSBHandler()
    {
        // Represents a WMI event query in WQL format (Windows Query Language)
        ManagementScope scope = new ManagementScope("root\\CIMV2");

        // Represents a scope (namespace)for management operations.		
        scope.Options.EnablePrivileges = true;

        try
        {
            WqlEventQuery query = new WqlEventQuery();

            query.EventClassName = "__InstanceCreationEvent";
            query.WithinInterval = new TimeSpan(0, 0, 3);
            query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
            
            _watcher = new ManagementEventWatcher(scope, query);

            //adds event handler that’s is fired when the insertion event occurs
            _watcher.EventArrived += new EventArrivedEventHandler(USBInseted);

            //run the watcher
            _watcher.Start();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);

            if (_watcher != null)
                _watcher.Stop();
        }

        using (FileStream stream = new FileStream(@"C:\USB_Log.txt", FileMode.Append))
        {
            _writer = new StreamWriter(stream);
        }
    }

    public void USBInseted(object sender, EventArgs e)
    {
        _writer.WriteLine("USB device is inserted at " + DateTime.Now.ToString());
    }

    // Important note: you should stop the watcher before exiting the application or else an excption is thrown  
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_watcher != null)
            _watcher.Stop();
    }

}

Open in new window

0
 

Author Closing Comment

by:jdcoburn
ID: 35090649
i haven't tried it yet, but it looks complete. the url reference is titled to what i am looking for.
0
 

Author Comment

by:jdcoburn
ID: 35107968
hi -- where does the syntax "query.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'"; come from? i'd like to refine the query so it only detects my device adding or leaving the usb enumeration.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Windows Media Player 2 31
Expression Evaluater 3 37
What is Microsoft.Exchange.WebServices.Data.ExchangeService in PowerShell? 4 33
C# MVC Insert Multiple Row into DB 2 30
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…

790 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question