Домой Windows Form Прослушивание USB порта на вставку и извлечение USB устройств и вывода информации...

Прослушивание USB порта на вставку и извлечение USB устройств и вывода информации о них с помощью WMI: Справочник по C#

564
0


using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Management;
using DevExpress.XtraBars.Alerter;
namespace usbport
{
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
public Form1()
{
InitializeComponent();
}
////used to subscribes to temporary event notifications based on a specified event query.
ManagementEventWatcher w = null;
ManagementEventWatcher w1 = null;

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (w != null)
w.Stop();

if (w1 != null)
w1.Stop();
}
public void lisBoxCtl1(string text)
{
try
{
if (this.InvokeRequired)
BeginInvoke(new MethodInvoker(delegate
{
listBox1.Items.Add(text);
}));
else
{
listBox1.Items.Add(text);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

public void alertControl(AlertInfo info)
{
try
{
if (this.InvokeRequired)
BeginInvoke(new MethodInvoker(delegate
{
//info = new AlertInfo("New Window", "Text");
alertControl1.Show(this, info);
}));
else
{
//info = new AlertInfo("New Window", "Text");
alertControl1.Show(this, info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

public void USBInseted(object sender, EventArgs e)
{
lisBoxCtl1("Вставлено USB устройство " + DateTime.Now.ToString());
}

public void USBDelection(object sender, EventArgs e)
{
lisBoxCtl1("USB устройство было извлечено " + DateTime.Now.ToString());
}

private void Form1_Load(object sender, EventArgs e)
{
AddUSBHandler();
EjectUSBHandler();
Hide();
ShowInTaskbar = false;
notifyIcon1.Visible = true;
}

void AddUSBHandler()
{
WqlEventQuery q;// 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
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceCreationEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveType=2)";
//q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
w = new ManagementEventWatcher(scope, q);

//adds event handler that’s is fired when the insertion event occurs
w.EventArrived += new EventArrivedEventHandler(USBInseted);
w.EventArrived += new EventArrivedEventHandler(OnWMIEvent);
w.Start();//run the watcher
}
catch (Exception e)
{
MessageBox.Show(e.Message);
if (w != null)
w.Stop();
}
}

void EjectUSBHandler()
{
WqlEventQuery q;// 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
{
q = new WqlEventQuery();
q.EventClassName = "__InstanceDeletionEvent";
q.WithinInterval = new TimeSpan(0, 0, 3);
q.Condition = @"TargetInstance isa 'Win32_LogicalDisk' and (TargetInstance.DriveType=2)";
//  q.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
w1 = new ManagementEventWatcher(scope, q);

//adds event handler that’s is fired when the insertion event occurs
w1.EventArrived += new EventArrivedEventHandler(USBDelection);
w1.EventArrived += new EventArrivedEventHandler(OnWMIEventDelection);
w1.Start();//run the watcher
}
catch (Exception e)
{
MessageBox.Show(e.Message);
if (w1 != null)
w1.Stop();
}
}

public void OnWMIEvent(object sender, EventArrivedEventArgs e)
{
PropertyData p = e.NewEvent.Properties["TargetInstance"];
if (p != null)
{
ManagementBaseObject mbo = p.Value as ManagementBaseObject;
//

PropertyData volumeName = mbo.Properties["VolumeName"];
// PropertyData model = mbo.Properties["Model"];
PropertyData freespace = mbo.Properties["FreeSpace"];//(ulong)volume["FreeSpace"];
PropertyData size = mbo.Properties["Size"];
PropertyData deviceid = mbo.Properties["DeviceID"];
PropertyData drivetype = mbo.Properties["DriveType"];
PropertyData driveSerial = mbo.Properties["VolumeSerialNumber"];
PropertyData driveGUID = mbo.Properties["PNPDeviceID"];

// Show a sample alert window.


//// Show a sample alert window.
AlertInfo info = new AlertInfo("Вставлено USB устройство " + Environment.NewLine + DateTime.Now.ToString(),
string.Format("{0}: {1}", "VolumeName", volumeName.Value) + Environment.NewLine +
string.Format("{0}: {1}", "FreeSpace", FormatByteCount((ulong)freespace.Value)) + Environment.NewLine +
string.Format("{0}: {1}", "Size", FormatByteCount((ulong)size.Value)) + Environment.NewLine +
string.Format("{0}: {1}", "DeviceID", deviceid.Value) + Environment.NewLine +
string.Format("{0}: {1}", "DriveType", drivetype.Value) + Environment.NewLine +
string.Format("{0}: {1}", "VolumeSerialNumber", driveSerial.Value) + Environment.NewLine +
string.Format("{0}: {1}", "PNPDeviceID", driveGUID.Value)
);
alertControl(info);

lisBoxCtl1(string.Format("{0}: {1}", "VolumeName", volumeName.Value));
//lisBoxCtl1(string.Format("{0}: {1}", "Model", model.Value));

lisBoxCtl1(string.Format("{0}: {1}", "FreeSpace", FormatByteCount((ulong)freespace.Value)));
lisBoxCtl1(string.Format("{0}: {1}", "Size", FormatByteCount((ulong)size.Value)));

lisBoxCtl1(string.Format("{0}: {1}", "DeviceID", deviceid.Value));
lisBoxCtl1(string.Format("{0}: {1}", "DriveType", drivetype.Value));
lisBoxCtl1(string.Format("{0}: {1}", "VolumeSerialNumber", driveSerial.Value));
lisBoxCtl1(string.Format("{0}: {1}", "PNPDeviceID", driveGUID.Value));
lisBoxCtl1("");
}
}

public void OnWMIEventDelection(object sender, EventArrivedEventArgs e)
{
PropertyData p = e.NewEvent.Properties["TargetInstance"];
if (p != null)
{
ManagementBaseObject mbo = p.Value as ManagementBaseObject;
//

PropertyData volumeName = mbo.Properties["VolumeName"];
// PropertyData model = mbo.Properties["Model"];
PropertyData freespace = mbo.Properties["FreeSpace"];//(ulong)volume["FreeSpace"];
PropertyData size = mbo.Properties["Size"];
PropertyData deviceid = mbo.Properties["DeviceID"];
PropertyData drivetype = mbo.Properties["DriveType"];
PropertyData driveSerial = mbo.Properties["VolumeSerialNumber"];
PropertyData driveGUID = mbo.Properties["PNPDeviceID"];

// Show a sample alert window.
AlertInfo info = new AlertInfo("USB устройство было извлечено " + Environment.NewLine + DateTime.Now.ToString(),
string.Format("{0}: {1}", "VolumeName", volumeName.Value) + Environment.NewLine +
string.Format("{0}: {1}", "FreeSpace", FormatByteCount((ulong)freespace.Value)) + Environment.NewLine +
string.Format("{0}: {1}", "Size", FormatByteCount((ulong)size.Value)) + Environment.NewLine +
string.Format("{0}: {1}", "DeviceID", deviceid.Value) + Environment.NewLine +
string.Format("{0}: {1}", "DriveType", drivetype.Value) + Environment.NewLine +
string.Format("{0}: {1}", "VolumeSerialNumber", driveSerial.Value) + Environment.NewLine +
string.Format("{0}: {1}", "PNPDeviceID", driveGUID.Value)
);
alertControl(info);
lisBoxCtl1(string.Format("{0}: {1}", "VolumeName", volumeName.Value));
//lisBoxCtl1(string.Format("{0}: {1}", "Model", model.Value));

lisBoxCtl1(string.Format("{0}: {1}", "FreeSpace", FormatByteCount((ulong)freespace.Value)));
lisBoxCtl1(string.Format("{0}: {1}", "Size", FormatByteCount((ulong)size.Value)));

lisBoxCtl1(string.Format("{0}: {1}", "DeviceID", deviceid.Value));
lisBoxCtl1(string.Format("{0}: {1}", "DriveType", drivetype.Value));
lisBoxCtl1(string.Format("{0}: {1}", "VolumeSerialNumber", driveSerial.Value));
lisBoxCtl1(string.Format("{0}: {1}", "PNPDeviceID", driveGUID.Value));
lisBoxCtl1("");
}
}

#region Size USB
private const int KB = 1024;
private const int MB = KB * 1000;
private const int GB = MB * 1000;

private string FormatByteCount(ulong bytes)
{
string format = null;

if (bytes < KB)
{
format = String.Format("{0} Bytes", bytes);
}
else if (bytes < MB)
{
bytes = bytes / KB;
format = String.Format("{0} KB", bytes.ToString("N"));
}
else if (bytes < GB)
{
double dree = bytes / MB;
format = String.Format("{0} MB", dree.ToString("N1"));
}
else
{
double gree = bytes / GB;
format = String.Format("{0} GB", gree.ToString("N1"));
}

return format;
}

#endregion

private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
Show();
Activate();
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
notifyIcon1.Visible = false;
}

}
}

Прослушивание USB порта на вставку и извлечение USB устройств и вывода информации о них с помощью WMI: Справочник по C#

0.00 (0%) 0 votes

ЧИТАТЬ ТАКЖЕ:  Загрузка центрального процессора: Справочник по C#

ОСТАВЬТЕ ОТВЕТ

Пожалуйста, введите ваш комментарий!
пожалуйста, введите ваше имя здесь