Bashar Kokash' Blog

.Net Framework, windows and web development.

This site

Resources

Friends

Sponsors

  • MaximumASP
  • Packet Sniffer

March 2008 - Posts

USB Port Insert / Remove detection using WMI (Source Code)

This post will contain only a simple console application source code about how to detected the insertion or removal of any USB device, for more details on the code please read USB Port Insert / Remove detection using WMI

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WMITestConsolApplication
{

class Program
{

static void Main(string[] args)
{

AddInsetUSBHandler();
AddRemoveUSBHandler();
for (; ; ) ;

}

static ManagementEventWatcher w = null;

public static void AddRemoveUSBHandler()
{

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

try
{

q = new WqlEventQuery();
q.EventClassName =
"__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition =
@"TargetInstance ISA 'Win32_USBControllerdevice'";
w =
new ManagementEventWatcher(scope, q);
w.EventArrived +=
new EventArrivedEventHandler(USBRemoved);
w.Start();

}

catch (Exception e)
{

Console.WriteLine (e.Message);
if (w != null)
     
w.Stop();

}

}

static void AddInsetUSBHandler()
{

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

try
{

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

}

catch (Exception e)
{

Console.WriteLine (e.Message);
if (w != null)
     
w.Stop();

}

}

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

Console.WriteLine("A USB device inserted");

}

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

Console.WriteLine("A USB device removed");

}

}

}

Posted: Mar 15 2008, 02:58 PM by BasharKokash | with 2 comment(s)
Filed under: , ,
Microsoft released the beta 1 version of Silverlight2

Microsoft announces the beta 1 version of Silverlight 2 Mix08

Install it then discover the new server controls.

Resources: