Hi, i have a windows application in vb.net. I just want to detect the USB pen port whether is it connected or not, if connected then i want to copy and remove the file from the pen derive.
detect USB device
Collapse
X
-
Tags: None
-
Comment
-
may be it work for you
class usbdetect
{
public static void Main()
{
usbdetect we = new usbdetect();
ManagementEvent Watcher w= null;
WqlEventQuery q;
ManagementOpera tionObserver observer = new
ManagementOpera tionObserver();
// Bind to local machine
ManagementScope scope = new ManagementScope ("root\\CIMV2") ;
scope.Options.E nablePrivileges = true; //sets required privilege
try
{
q = new WqlEventQuery() ;
q.EventClassNam e = "__InstanceOper ationEvent";
q.WithinInterva l = new TimeSpan(0,0,3) ;
q.Condition = @"TargetInstanc e ISA 'Win32_USBContr oller'";
Console.WriteLi ne(q.QueryStrin g);
w = new ManagementEvent Watcher(scope, q);
w.EventArrived += new EventArrivedEve ntHandler(we.Us bEventArrived);
w.Start();
Console.ReadLin e(); // block main thread for test purposes
}
catch(Exception e)
{
Console.WriteLi ne(e.Message);
}
finally
{
w.Stop();
}
}
public void UsbEventArrived (object sender, EventArrivedEve ntArgs e)
{
//Get the Event object and display it
foreach(Propert yData pd in e.NewEvent.Prop erties)
{
ManagementBaseO bject mbo = null;
if(( mbo = pd.Value as ManagementBaseO bject) != null)
{
foreach(Propert yData prop in mbo.Properties)
Console.WriteLi ne("{0} - {1}", prop.Name, prop.Value);
}
}
}
}Comment
-
or check this http://www.icsharpcode.net/OpenSourc...b/default.aspx
this one is for printer so modify it for usb
using System.Manageme nt;
namespace zedilabs.com
{
class PrinterOffline
{
[STAThread]
static void Main(string[] args)
{
// Set management scope
ManagementScope scope = new ManagementScope (@"\root\cimv2" );
scope.Connect() ;
// Select Printers from WMI Object Collections
ManagementObjec tSearcher searcher = new
ManagementObjec tSearcher("SELE CT * FROM Win32_Printer") ;
string printerName = "";
foreach (ManagementObje ct printer in searcher.Get())
{
printerName = printer["Name"].ToString().ToL ower();
if (printerName.Eq uals(@"hp deskjet 930c"))
{
Console.WriteLi ne("Printer = " + printer["Name"]);
if (printer["WorkOfflin e"].ToString().ToL ower().Equals(" true"))
{
// printer is offline by user
Console.WriteLi ne("Your Plug-N-Play printer is not connected.");
}
else
{
// printer is not offline
Console.WriteLi ne("Your Plug-N-Play printer is connected.");
}
}
}
}
}
}Comment
Comment