using System; using System.Collections.Generic; using System.Globalization; using System.Management; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace UsbDemo { internal enum WmiType { Win32_Processor, Win32_PerfFormattedData_PerfOS_Memory, Win32_PhysicalMemory, Win32_NetworkAdapterConfiguration, Win32_LogicalDisk } /// <summary> /// 获取硬盘号和CPU号 /// </summary> public class WmiHelper { public class MachineNumber { static Dictionary<string, ManagementObjectCollection> WmiDict = new Dictionary<string, ManagementObjectCollection>(); static MachineNumber() { var names = Enum.GetNames(typeof(WmiType)); foreach (string name in names) { WmiDict.Add(name, new ManagementObjectSearcher("SELECT * FROM " + name).Get()); } } /// <summary> /// 获取硬盘号码 /// </summary> /// <returns></returns> public static string GetHardDiskNumber() { var query = WmiDict[WmiType.Win32_LogicalDisk.ToString()]; //var collection = query.Get(); string result = string.Empty; foreach (var obj in query) { result = obj["VolumeSerialNumber"].ToString(); break; } return result; } /// <summary> /// 获取CPU号码 /// </summary> /// <returns></returns> public static string GetCPUNumber() { var query = WmiDict[WmiType.Win32_Processor.ToString()]; //var collection = query.Get(); string result = string.Empty; foreach (var obj in query) { result = obj["Processorid"].ToString(); break; } return result; } /// <summary> /// 获取内存编号 /// </summary> /// <returns></returns> public static string GetMemoryNumber() { var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()]; //var collection = query.Get(); string result = string.Empty; foreach (var obj in query) { result = obj["PartNumber"].ToString(); break; } return result; } /// <summary> /// 获取硬盘信息 /// </summary> /// <returns></returns> public static string HardDiskInfo() { DriveInfo[] drives = DriveInfo.GetDrives(); StringBuilder sr = new StringBuilder(); foreach (DriveInfo drive in drives) { if (drive.IsReady) { var val1 = (double)drive.TotalSize / 1024 / 1024; var val2 = (double)drive.TotalFreeSpace / 1024 / 1024; sr.AppendFormat("{0}:{2}/{3}MB/{4}MB/{1}%可用;" + Environment.NewLine, drive.Name, string.Format("{0:F2}", val2 / val1 * 100), drive.DriveFormat, (long)val1, (long)val2); } } return sr.ToString(); } /// <summary> /// 获取操作系统信息 /// </summary> /// <returns></returns> public static string OSInfo() { StringBuilder sr = new StringBuilder(); sr.AppendFormat("机器名:{0};操作系统:{1};系统文件夹:{2};语言:{3};.NET:{4};当前目录:{5};当前用户:{6};", Environment.MachineName, Environment.OSVersion, Environment.SystemDirectory, CultureInfo.InstalledUICulture.EnglishName, Environment.Version, Environment.CurrentDirectory, Environment.UserName); return sr.ToString(); } /// <summary> /// 获取网卡信息 /// </summary> /// <returns></returns> public static string NetworkInfo() { StringBuilder sr = new StringBuilder(); string host = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName(host); sr.Append("IPv4:" + ipEntry.AddressList[0] + "/"); sr.Append("IPv6:"); ipEntry = Dns.GetHostEntry(host); sr.Append("IPv6:" + ipEntry.AddressList[0] + ";"); sr.Append("MAC:"); var query = WmiDict[WmiType.Win32_NetworkAdapterConfiguration.ToString()]; foreach (var obj in query) { if (obj["IPEnabled"].ToString() == "True") sr.Append(obj["MacAddress"] + ";"); } return sr.ToString(); } /// <summary> /// 获取内存信息 /// </summary> /// <returns></returns> public static string MemoryInfo() { StringBuilder sr = new StringBuilder(); try { long capacity = 0; var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()]; int index = 1; foreach (var obj in query) { //sr.Append("内存" + index + "频率:" + obj["ConfiguredClockSpeed"] + ";"); capacity += Convert.ToInt64(obj["Capacity"]); index++; } sr.Append("总物理内存:"); sr.Append(capacity / 1024 / 1024 + "MB;"); query = WmiDict[WmiType.Win32_PerfFormattedData_PerfOS_Memory.ToString()]; sr.Append("总可用内存:"); long available = 0; foreach (var obj in query) { available += Convert.ToInt64(obj.Properties["AvailableMBytes"].Value); } sr.Append(available + "MB;"); sr.AppendFormat("{0:F2}%可用; ", (double)available / (capacity / 1024 / 1024) * 100); } catch (Exception ex) { sr.Append("异常信息:" + ex.Message); } return sr.ToString(); } /// <summary> /// 获取CPU信息 /// </summary> /// <returns></returns> public static string CpuInfo() { StringBuilder sr = new StringBuilder(); var query = WmiDict[WmiType.Win32_Processor.ToString()]; foreach (var obj in query) { sr.Append("厂商:" + obj["Manufacturer"] + ";"); sr.Append("产品名称:" + obj["Name"] + ";"); sr.Append("最大频率:" + obj["MaxClockSpeed"] + ";"); sr.Append("当前频率:" + obj["CurrentClockSpeed"] + ";"); } return sr.ToString(); } } } }
using System; using System.Management; namespace UsbDemo { /// <summary> /// USB控制设备类型 /// </summary> public struct ProcessInfo { /// <summary> /// USB控制器设备ID /// </summary> public String Antecedent; /// <summary> /// USB即插即用设备ID /// </summary> public String Dependent; } class ProcessWatcher { /// <summary> /// USB插入事件监视 /// </summary> private ManagementEventWatcher insertWatcher = null; /// <summary> /// USB拔出事件监视 /// </summary> private ManagementEventWatcher removeWatcher = null; /// <summary> /// 添加USB事件监视器 /// </summary> /// <param name="usbInsertHandler">USB插入事件处理器</param> /// <param name="usbRemoveHandler">USB拔出事件处理器</param> /// <param name="withinInterval">发送通知允许的滞后时间</param> public Boolean AddUSBEventWatcher(EventArrivedEventHandler usbInsertHandler, EventArrivedEventHandler usbRemoveHandler, TimeSpan withinInterval) { try { ////创建WQL事件查询,用于实例创建 //var qCreate = new WqlEventQuery("__InstanceCreationEvent",TimeSpan.FromSeconds(1),"TargetInstance ISA 'Win32_Process'"); ////创建WQL事件查询,用于实例删除 //var qDelete = new WqlEventQuery("__InstanceDeletionEvent",TimeSpan.FromSeconds(1), "TargetInstance ISA 'Win32_Process'"); ////创建事件查询的侦听器(ManagementEventWatcher) //var wCreate = new ManagementEventWatcher(qCreate); //var wDelete = new ManagementEventWatcher(qDelete); ////事件注册代码 //wCreate.EventArrived += (sender, e) => //{ // Console.WriteLine("运行:{0}", GetInfo(e.NewEvent)); //}; //wDelete.EventArrived += (sender, e) => //{ // Console.WriteLine("关闭:{0}", GetInfo(e.NewEvent)); //}; ////异步开始侦听 //wCreate.Start(); //wDelete.Start(); //Console.WriteLine("按任意键停止监控"); //Console.ReadKey(true); // 进程执行监视 if (usbInsertHandler != null) { WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent", withinInterval, "TargetInstance ISA 'Win32_Process'"); insertWatcher = new ManagementEventWatcher( InsertQuery); insertWatcher.EventArrived += usbInsertHandler; insertWatcher.Start(); } // 进程结束监视 if (usbRemoveHandler != null) { WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent", withinInterval, "TargetInstance ISA 'Win32_Process'"); removeWatcher = new ManagementEventWatcher( RemoveQuery); removeWatcher.EventArrived += usbRemoveHandler; removeWatcher.Start(); } return true; } catch (Exception) { RemoveUSBEventWatcher(); return false; } } /// <summary> /// 移去USB事件监视器 /// </summary> public void RemoveUSBEventWatcher() { if (insertWatcher != null) { insertWatcher.Stop(); insertWatcher = null; } if (removeWatcher != null) { removeWatcher.Stop(); removeWatcher = null; } } //输出事件对应的ManagementBaseObject(本例中的Win32_Process实例)的信息 static string GetInfo(ManagementBaseObject mobj) { var instance = (ManagementBaseObject)mobj["TargetInstance"]; return string.Format("{0} - {1}", instance["Name"], DateTime.Now); } /// <summary> /// 定位发生插拔的USB设备 /// </summary> /// <param name="e">USB插拔事件参数</param> /// <returns>发生插拔现象的USB控制设备ID</returns> public static ProcessInfo[] WhoControllerDevice(EventArrivedEventArgs e) { ManagementBaseObject instance = e.NewEvent["TargetInstance"] as ManagementBaseObject; return new ProcessInfo[1] { new ProcessInfo { Antecedent = instance["Name"].ToString(), Dependent = instance["Name"].ToString() } }; } } }
http://blog.csdn.net/asciil/article/details/6931429
http://www.cnblogs.com/password1/p/5870751.html