Solved

USB NOTIFICATION

Posted on 2011-03-09
3
645 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

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…
This video discusses moving either the default database or any database to a new volume.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now