Wpf/winform USB Device Pull-plug view via WMI

Source: Internet
Author: User
Tags foreach datetime split trim

Text used to open source class, Baidu Cloud Download: Link: http://pan.baidu.com/s/1kVJfGsJ Password: Tkna

1, first USB tool class DriveDetector.cs:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Management;
Using System.Text;
Using System.Threading.Tasks;
Namespace StarsCloud.Comet.Common
{
<summary>
USB Control device Type
</summary>
public struct Usbcontrollerdevice
{
<summary>
USB Controller Device ID
</summary>
Public String Antecedent;
<summary>
USB Plug and Play device ID
</summary>
Public String Dependent;
}
<summary>
Monitor USB Plug and pull
</summary>
public partial class USB
{
<summary>
USB Insert Event Monitoring
</summary>
Private ManagementEventWatcher insertwatcher = null;
<summary>
USB Pull Out Event monitoring
</summary>
Private ManagementEventWatcher removewatcher = null;
<summary>
Add USB Event Monitor
</summary>
<param name= "Usbinserthandler" >usb Insert Event Processor </param>
<param name= "Usbremovehandler" >usb Unplug event processor </param>
<param name= "Withininterval" > Send notifications Allowed Latency </param>
Public Boolean Addusbeventwatcher (Eventarrivedeventhandler Usbinserthandler, Eventarrivedeventhandler Usbremovehandler, TimeSpan Withininterval)
{
Try
{
Managementscope Scope = new Managementscope ("root\\cimv2");
Scope.Options.EnablePrivileges = true;
USB Insert Monitor
if (Usbinserthandler!= null)
{
Wqleventquery insertquery = new Wqleventquery ("__InstanceCreationEvent",
Withininterval,
"TargetInstance Isa ' win32_usbcontrollerdevice '");
Insertwatcher = new ManagementEventWatcher (Scope, InsertQuery);
Insertwatcher.eventarrived + = Usbinserthandler;
Insertwatcher.start ();
}
USB Pull Out Monitor
if (Usbremovehandler!= null)
{
Wqleventquery removequery = new Wqleventquery ("__InstanceDeletionEvent",
Withininterval,
"TargetInstance Isa ' win32_usbcontrollerdevice '");
Removewatcher = new ManagementEventWatcher (Scope, removequery);
Removewatcher.eventarrived + = Usbremovehandler;
Removewatcher.start ();
}
return true;
}
catch (Exception)
{
Removeusbeventwatcher ();
return false;
}
}
<summary>
To remove the USB event monitor
</summary>
public void Removeusbeventwatcher ()
{
if (Insertwatcher!= null)
{
Insertwatcher.stop ();
Insertwatcher = null;
}
if (Removewatcher!= null)
{
Removewatcher.stop ();
Removewatcher = null;
}
}
<summary>
Locating the USB device where the plug occurred
</summary>
<param name= "E" >usb plug event parameters </param>
<returns> USB control device id</returns> with plug-and-pull phenomenon
public static usbcontrollerdevice[] Whousbcontrollerdevice (Eventarrivedeventargs e)
{
Managementbaseobject MBO = e.newevent["TargetInstance"] as Managementbaseobject;
if (MBO!= null && MBO. Classpath.classname = = "Win32_USBControllerDevice")
{
String Antecedent = (mbo["Antecedent"] as String). Replace ("\", ""). Split (new char[] {' = '}) [1];
String Dependent = (mbo["Dependent"] as String). Replace ("\", ""). Split (new char[] {' = '}) [1];
return new Usbcontrollerdevice[1] {new Usbcontrollerdevice {Antecedent = Antecedent, Dependent = Dependent}};
}
return null;
}
}
}

2, in the WPF or Control window CS, call:

Common.usb Ezusb = new Common.usb ();

BOOL Isopeningcamera = false;
DateTime benginopen = DateTime.Now;

Note: Because of the USB plug, the event will trigger 3 times, I use a timestamp record here, in the 10-second range of USB plug is not processed. Of course, there are problems.

Registering Events:

Ezusb.addusbeventwatcher (Usbeventhandler, Usbeventhandler, New TimeSpan (0, 0,3));

3. Event implementation:

private void Usbeventhandler (Object sender, Eventarrivedeventargs e)
{
if (E.newevent.classpath.classname = = "__InstanceCreationEvent")
{
foreach (Usbcontrollerdevice Device in Common.USB.WhoUSBControllerDevice (e))
{
int i = 0;
Match match = Regex.match (device.dependent, "vid_[0-9| a-f]{4}&pid_[0-9| A-F]{4} ");
if (match. Success)
{
Hidd_vidpid Entity;
Entity.vendorid = convert.touint16 (match.    Value.substring (4, 4), 16); Vendor identification
Entity.productid = convert.touint16 (match.  Value.substring (13, 4), 16); Product number
Pnpentityinfo[] model = Splash.IO.PORTS.USB.WhoPnPEntity (device.dependent);
If model!= null && model. Length > 0)
{//Get a USB device
foreach (Pnpentityinfo pn in model)
{
if (PN. Description.indexof (staticresourcehandller. Chemical camera name. Value) >= 0 && PN. Name.trim (). IndexOf (staticresourcehandller. Chemical camera description. Value) >= 0)
{
MessageBox.Show (PN. Description);
if (Isopeningcamera = = False)
{
Isopeningcamera = true;
This. Dispatcher.invoke (() The New Action (() => {
if (Benginopen.addseconds < DateTime.Now)
{
Benginopen = DateTime.Now;
Cameraopen (TRUE);
}
Isopeningcamera = false;
}));
}
}
else if (PN. Description.indexof (staticresourcehandller. Chemical com matching description. Value) >= 0)
{
MessageBox.Show (PN. Description);
if (Isopeningcamera = = False)
{
Isopeningcamera = true;

if (Benginopen.addseconds < DateTime.Now)
{
Benginopen = DateTime.Now;
Remove COM port
String comname = pn. Name.replace (staticresourcehandller.com matching description. Value, ""). Replace ("(", ""). Replace (")", ""). Trim ();
List<pnpentityinfo> allexitescom = model. Where (a => a.name.replace (staticresourcehandller. Dry chemical com Match description. Value, ""). Replace ("(", ""). Replace (")", ""). Trim () = =
staticresourcehandller.com mouth. Value
). ToList ()//See if there is an identical port configuration. If anything, the instructions are configured,
if (staticresourcehandller. Mirror com port. Value!= comname)
{//high magnification mirror not occupied
Staticresourcehandller. Configure the chemical COM port (comname);
}
}
Isopeningcamera = false;
}
}
}
}
}
}
}
else if (e.newevent.classpath.classname = "__InstanceDeletionEvent")
{
This. SetText ("USB pull-out Time:" + DateTime.Now + "\ r \ n");
}
This. SetText ("USB Insert Time:" + DateTime.Now + "\ r \ n");
This. SetText ("\tantecedent:" + device.antecedent + "\ r \ n");
This. SetText ("\tdependent:" + device.dependent + "\ r \ n");
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.