Friday, June 18, 2010

window service for USB detection using C#

USB has no notion of a "port number". Enumerating USB devices and getting notifications that one was attached or removed normally requires heavy-duty C++ code.

In .net when we insert a usb drive to computer shell detect it give a message to operating system, it calls the “WndProc” of bcl.
WM_ChangedDevice message is broadcasted whenever something relevant occurs in a device connected to Microsoft windows. For this matter, there are two events which we will need to trap, the DBT_DEVICEARRIVAL and the DBT_DEVICEREMOVECOMPLETE.
Both events are handled the same way, the only difference being that DBT_DEVICEARRIVAL detects a volume being inserted, and the DBT_DEVICEREMOVECOMPLETE detects that a volume was removed.
Here we will discuss how to detect a USB device and find its vendorID(VID) and productID(PID).
First create a window service in C#. Go in constructor of window service file and use the following code there.
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
"DoDyLog");

eventLog1.Source = "DoDyLogSourse";
// the event log source by which

//the application is registered on the computer

eventLog1.Log = "DoDyLog";


use onstart and onstop events of window service to make log file for this service. follow this code:
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("My service is started now");
InsertUSBHandler();
RemoveUSBHandler();
}


protected override void OnStop()
{
eventLog1.WriteEntry("My service is going to stop now");
}
//Defination for InsertUSBHandler
static void InsertUSBHandler()
{

WqlEventQuery wqlEventQueryObj;
ManagementScope scope = new ManagementScope("root\\CIMV2");
scope.Options.EnablePrivileges = true;

try
{

wqlEventQueryObj = new WqlEventQuery();
wqlEventQueryObj.EventClassName = "__InstanceCreationEvent";
wqlEventQueryObj.WithinInterval = new TimeSpan(0, 0, 3);
wqlEventQueryObj.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
managementEventWatcherObj = new ManagementEventWatcher(scope, wqlEventQueryObj);
managementEventWatcherObj.EventArrived += new EventArrivedEventHandler(USBAdded);
managementEventWatcherObj.Start();

}
catch (Exception e)
{
if (managementEventWatcherObj != null)
managementEventWatcherObj.Stop();
}

}


public static void USBAdded(object sender, EventArgs e)
{

MessageBox.Show("New USB found");
USBSerialNumber usb = new USBSerialNumber();
//string serial = usb.getSerialNumberFromDriveLetter("f:");
usb.FindVendorID();
}

Here in USB added method we are showing a message that "New USB found". by doing all this we can detect a usb that is inserted. but we can also find its serial number and usb's vendor ID and Product ID. By doing this we can show any particular message or run any particular application on insertion of particular USB. so that our window service bound to particular device. i have done all this and it is in running state now.
We can also implement more functionality regarding USB here depending upon requirement. Please let me know if it helps you or is there any way to do all these. i am always for your help.Happy coding!!!!!:)