本文共 20244 字,大约阅读时间需要 67 分钟。
private void button1_Click(object sender, EventArgs e) { textBox1.Text = ""; foreach (string s in listBox1.SelectedItems) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From "+s); foreach (ManagementObject mo in searcher.Get()) { textBox1.AppendText("============" + s+ "开始======\r\n"); foreach (PropertyData pd in mo.Properties) { textBox1.Text += pd.Name + " :: "; if (pd.Value != null) { textBox1.Text += pd.Value.ToString(); } textBox1.Text += "\r\n"; } textBox1.AppendText("============" + s + "结束======\r\n\r\n\r\n"); //break; } } }
复制代码
复制代码
//获取主板序列号public string GetBIOSSerialNumber(){ try{ ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select From Win32_BIOS");string sBIOSSerialNumber = "";foreach (ManagementObject mo in searcher.Get()){ sBIOSSerialNumber = mo["SerialNumber"].ToString().Trim();}return sBIOSSerialNumber;}catch{ return "";}}//获取CPU序列号public string GetCPUSerialNumber(){ try{ ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select From Win32_Processor");string sCPUSerialNumber = "";foreach (ManagementObject mo in searcher.Get()){ sCPUSerialNumber = mo["ProcessorId"].ToString().Trim();}return sCPUSerialNumber;}catch{ return "";}}//获取硬盘序列号public string GetHardDiskSerialNumber(){ try{ ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT FROM Win32_PhysicalMedia");string sHardDiskSerialNumber = "";foreach (ManagementObject mo in searcher.Get()){ sHardDiskSerialNumber = mo["SerialNumber"].ToString().Trim();break;}return sHardDiskSerialNumber;}catch{ return "";}}//获取网卡地址public string GetNetCardMACAddress(){ try{ ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL) AND (Manufacturer <> 'Microsoft'))");string NetCardMACAddress = "";foreach (ManagementObject mo in searcher.Get()){ NetCardMACAddress = mo["MACAddress"].ToString().Trim();}return NetCardMACAddress;}catch{ return "";}}复制代码在很多情况下,你可能都需要得到微机的硬件信息。比如:你想给你的软件加锁,不让别人随便访问。
最有效的办法是获取CPU的序列号,然后让你的软件只能运行在有这样的CPU序列号的机器上。众所周知,CPU序列号是唯一的!因此,这样就可以为你的软件加锁了。powered by 25175.net
另外一个需要硬盘信息的例子是:硬盘有几个分区,每个分区各有多少剩余空间。当你正在做一个多媒体应用程序的时候,你可能也需要获得有关声卡、显卡的硬件信息。
本应用程序另一个精彩的应用是:获取有关系统内存的信息,如内存地址,内存设备等等。
首先,你必须知道这个应用程序的功能是使用System.Management这个类得到的。因此,你需要加上下面的这句话:
using System.Management;
为了获取硬件信息,你还需要创建一个ManagementObjectSearcher 对象。
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
// 硬件
Win32_Processor, // CPU 处理器 Win32_PhysicalMemory, // 物理内存条 Win32_Keyboard, // 键盘 Win32_PointingDevice, // 点输入设备,包括鼠标。 Win32_FloppyDrive, // 软盘驱动器 Win32_DiskDrive, // 硬盘驱动器 Win32_CDROMDrive, // 光盘驱动器 Win32_BaseBoard, // 主板 Win32_BIOS, // BIOS 芯片 Win32_ParallelPort, // 并口 Win32_SerialPort, // 串口 Win32_SerialPortConfiguration, // 串口配置 Win32_SoundDevice, // 多媒体设置,一般指声卡。 Win32_SystemSlot, // 主板插槽 (ISA & PCI & AGP) Win32_USBController, // USB 控制器 Win32_NetworkAdapter, // 网络适配器 Win32_NetworkAdapterConfiguration, // 网络适配器设置 Win32_Printer, // 打印机 Win32_PrinterConfiguration, // 打印机设置 Win32_PrintJob, // 打印机任务 Win32_TCPIPPrinterPort, // 打印机端口 Win32_POTSModem, // MODEM Win32_POTSModemToSerialPort, // MODEM 端口 Win32_DesktopMonitor, // 显示器 Win32_DisplayConfiguration, // 显卡 Win32_DisplayControllerConfiguration, // 显卡设置 Win32_VideoController, // 显卡细节。 Win32_VideoSettings, // 显卡支持的显示模式。// 操作系统
Win32_TimeZone, // 时区 Win32_SystemDriver, // 驱动程序 Win32_DiskPartition, // 磁盘分区 Win32_LogicalDisk, // 逻辑磁盘 Win32_LogicalDiskToPartition, // 逻辑磁盘所在分区及始末位置。 Win32_LogicalMemoryConfiguration, // 逻辑内存配置 Win32_PageFile, // 系统页文件信息 Win32_PageFileSetting, // 页文件设置 Win32_BootConfiguration, // 系统启动配置 Win32_ComputerSystem, // 计算机信息简要 Win32_OperatingSystem, // 操作系统信息 Win32_StartupCommand, // 系统自动启动程序 Win32_Service, // 系统安装的服务 Win32_Group, // 系统管理组 Win32_GroupUser, // 系统组帐号 Win32_UserAccount, // 用户帐号 Win32_Process, // 系统进程 Win32_Thread, // 系统线程 Win32_Share, // 共享 Win32_NetworkClient, // 已安装的网络客户端 Win32_NetworkProtocol, // 已安装的网络协议上面代码的Key是一个将被对应正确的数据填入的值。例如,获取CPU的信息,就需要把Key值设成Win32_Processor。所有Key可能的值,列举如下:
Win32_1394Controller
Win32_1394ControllerDeviceWin32_AccountWin32_AccountSIDWin32_ACEWin32_ActionCheckWin32_AllocatedResourceWin32_ApplicationCommandLineWin32_ApplicationServiceWin32_AssociatedBatteryWin32_AssociatedProcessorMemoryWin32_BaseBoardWin32_BaseServiceWin32_BatteryWin32_BinaryWin32_BindImageActionWin32_BIOSWin32_BootConfigurationWin32_BusWin32_CacheMemoryWin32_CDROMDriveWin32_CheckCheckWin32_CIMLogicalDeviceCIMDataFileWin32_ClassicCOMApplicationClassesWin32_ClassicCOMClassWin32_ClassicCOMClassSettingWin32_ClassicCOMClassSettingsWin32_ClassInfoActionWin32_ClientApplicationSettingWin32_CodecFileWin32_COMApplicationWin32_COMApplicationClassesWin32_COMApplicationSettingsWin32_COMClassWin32_ComClassAutoEmulatorWin32_ComClassEmulatorWin32_CommandLineAccessWin32_ComponentCategoryWin32_ComputerSystemWin32_ComputerSystemProcessorWin32_ComputerSystemProductWin32_COMSettingWin32_ConditionWin32_CreateFolderActionWin32_CurrentProbeWin32_DCOMApplicationWin32_DCOMApplicationAccessAllowedSettingWin32_DCOMApplicationLaunchAllowedSettingWin32_DCOMApplicationSettingWin32_DependentServiceWin32_DesktopWin32_DesktopMonitorWin32_DeviceBusWin32_DeviceMemoryAddressWin32_DeviceSettingsWin32_DirectoryWin32_DirectorySpecificationWin32_DiskDriveWin32_DiskDriveToDiskPartitionWin32_DiskPartitionWin32_DisplayConfigurationWin32_DisplayControllerConfigurationWin32_DMAChannelWin32_DriverVXDWin32_DuplicateFileActionWin32_EnvironmentWin32_EnvironmentSpecificationWin32_ExtensionInfoActionWin32_FanWin32_FileSpecificationWin32_FloppyControllerWin32_FloppyDriveWin32_FontInfoActionWin32_GroupWin32_GroupUserWin32_HeatPipeWin32_IDEControllerWin32_IDEControllerDeviceWin32_ImplementedCategoryWin32_InfraredDeviceWin32_IniFileSpecificationWin32_InstalledSoftwareElementWin32_IRQResourceWin32_KeyboardWin32_LaunchConditionWin32_LoadOrderGroupWin32_LoadOrderGroupServiceDependenciesWin32_LoadOrderGroupServiceMembersWin32_LogicalDiskWin32_LogicalDiskRootDirectoryWin32_LogicalDiskToPartitionWin32_LogicalFileAccessWin32_LogicalFileAuditingWin32_LogicalFileGroupWin32_LogicalFileOwnerWin32_LogicalFileSecuritySettingWin32_LogicalMemoryConfigurationWin32_LogicalProgramGroupWin32_LogicalProgramGroupDirectoryWin32_LogicalProgramGroupItemWin32_LogicalProgramGroupItemDataFileWin32_LogicalShareAccessWin32_LogicalShareAuditingWin32_LogicalShareSecuritySettingWin32_ManagedSystemElementResourceWin32_MemoryArrayWin32_MemoryArrayLocationWin32_MemoryDeviceWin32_MemoryDeviceArrayWin32_MemoryDeviceLocationWin32_MethodParameterClassWin32_MIMEInfoActionWin32_MotherboardDeviceWin32_MoveFileActionWin32_MSIResourceWin32_networkAdapterWin32_networkAdapterConfigurationWin32_networkAdapterSettingWin32_networkClientWin32_networkConnectionWin32_networkLoginProfileWin32_networkProtocolWin32_NTEventlogFileWin32_NTLogEventWin32_NTLogEventComputerWin32_NTLogEventLogWin32_NTLogEventUserWin32_ODBCAttributeWin32_ODBCDataSourceAttributeWin32_ODBCDataSourceSpecificationWin32_ODBCDriverAttributeWin32_ODBCDriverSoftwareElementWin32_ODBCDriverSpecificationWin32_ODBCSourceAttributeWin32_ODBCTranslatorSpecificationWin32_OnBoardDeviceWin32_OperatingSystemWin32_OperatingSystemQFEWin32_OSRecoveryConfigurationWin32_PageFileWin32_PageFileElementSettingWin32_PageFileSettingWin32_PageFileUsageWin32_ParallelPortWin32_PatchWin32_PatchFileWin32_PatchPackageWin32_PCMCIAControllerWin32_PerfWin32_PerfRawDataWin32_PerfRawData_ASP_ActiveServerPagesWin32_PerfRawData_ASPnet_114322_ASPnetAppsv114322Win32_PerfRawData_ASPnet_114322_ASPnetv114322Win32_PerfRawData_ASPnet_ASPnetWin32_PerfRawData_ASPnet_ASPnetApplicationsWin32_PerfRawData_IAS_IASAccountingClientsWin32_PerfRawData_IAS_IASAccountingServerWin32_PerfRawData_IAS_IASAuthenticationClientsWin32_PerfRawData_IAS_IASAuthenticationServerWin32_PerfRawData_InetInfo_InternetInformationServicesGlobalWin32_PerfRawData_MSDTC_DistributedTransactionCoordinatorWin32_PerfRawData_MSFTPSVC_FTPServiceWin32_PerfRawData_MSSQLSERVER_SQLServerAccessMethodsWin32_PerfRawData_MSSQLSERVER_SQLServerBackupDeviceWin32_PerfRawData_MSSQLSERVER_SQLServerBufferManagerWin32_PerfRawData_MSSQLSERVER_SQLServerBufferPartitionWin32_PerfRawData_MSSQLSERVER_SQLServerCacheManagerWin32_PerfRawData_MSSQLSERVER_SQLServerDatabasesWin32_PerfRawData_MSSQLSERVER_SQLServerGeneralStatisticsWin32_PerfRawData_MSSQLSERVER_SQLServerLatchesWin32_PerfRawData_MSSQLSERVER_SQLServerLocksWin32_PerfRawData_MSSQLSERVER_SQLServerMemoryManagerWin32_PerfRawData_MSSQLSERVER_SQLServerReplicationAgentsWin32_PerfRawData_MSSQLSERVER_SQLServerReplicationDistWin32_PerfRawData_MSSQLSERVER_SQLServerReplicationLogreaderWin32_PerfRawData_MSSQLSERVER_SQLServerReplicationMergeWin32_PerfRawData_MSSQLSERVER_SQLServerReplicationSnapshotWin32_PerfRawData_MSSQLSERVER_SQLServerSQLStatisticsWin32_PerfRawData_MSSQLSERVER_SQLServerUserSettableWin32_PerfRawData_netFramework_netCLRExceptionsWin32_PerfRawData_netFramework_netCLRInteropWin32_PerfRawData_netFramework_netCLRJitWin32_PerfRawData_netFramework_netCLRLoadingWin32_PerfRawData_netFramework_netCLRLocksAndThreadsWin32_PerfRawData_netFramework_netCLRMemoryWin32_PerfRawData_netFramework_netCLRRemotingWin32_PerfRawData_netFramework_netCLRSecurityWin32_PerfRawData_Outlook_OutlookWin32_PerfRawData_PerfDisk_PhysicalDiskWin32_PerfRawData_Perfnet_BrowserWin32_PerfRawData_Perfnet_RedirectorWin32_PerfRawData_Perfnet_ServerWin32_PerfRawData_Perfnet_ServerWorkQueuesWin32_PerfRawData_PerfOS_CacheWin32_PerfRawData_PerfOS_MemoryWin32_PerfRawData_PerfOS_ObjectsWin32_PerfRawData_PerfOS_PagingFileWin32_PerfRawData_PerfOS_ProcessorWin32_PerfRawData_PerfOS_SystemWin32_PerfRawData_PerfProc_FullImage_CostlyWin32_PerfRawData_PerfProc_Image_CostlyWin32_PerfRawData_PerfProc_JobObjectWin32_PerfRawData_PerfProc_JobObjectDetailsWin32_PerfRawData_PerfProc_ProcessWin32_PerfRawData_PerfProc_ProcessAddressSpace_CostlyWin32_PerfRawData_PerfProc_ThreadWin32_PerfRawData_PerfProc_ThreadDetails_CostlyWin32_PerfRawData_RemoteAccess_RASPortWin32_PerfRawData_RemoteAccess_RASTotalWin32_PerfRawData_RSVP_ACSPerRSVPServiceWin32_PerfRawData_Spooler_PrintQueueWin32_PerfRawData_TapiSrv_TelephonyWin32_PerfRawData_Tcpip_ICMPWin32_PerfRawData_Tcpip_IPWin32_PerfRawData_Tcpip_NBTConnectionWin32_PerfRawData_Tcpip_networkInterfaceWin32_PerfRawData_Tcpip_TCPWin32_PerfRawData_Tcpip_UDPWin32_PerfRawData_W3SVC_WebServiceWin32_PhysicalMediaWin32_PhysicalMemoryWin32_PhysicalMemoryArrayWin32_PhysicalMemoryLocationWin32_PNPAllocatedResourceWin32_PnPDeviceWin32_PnPEntityWin32_PointingDeviceWin32_PortableBatteryWin32_PortConnectorWin32_PortResourceWin32_POTSModemWin32_POTSModemToSerialPortWin32_PowerManagementEventWin32_PrinterWin32_PrinterConfigurationWin32_PrinterControllerWin32_PrinterDriverDllWin32_PrinterSettingWin32_PrinterShareWin32_PrintJobWin32_PrivilegesStatusWin32_ProcessWin32_ProcessorWin32_ProcessStartupWin32_ProductWin32_ProductCheckWin32_ProductResourceWin32_ProductSoftwareFeaturesWin32_ProgIDSpecificationWin32_ProgramGroupWin32_ProgramGroupContentsWin32_ProgramGroupOrItemWin32_PropertyWin32_ProtocolBindingWin32_PublishComponentActionWin32_QuickFixEngineeringWin32_RefrigerationWin32_RegistryWin32_RegistryActionWin32_RemoveFileActionWin32_RemoveIniActionWin32_ReserveCostWin32_ScheduledJobWin32_SCSIControllerWin32_SCSIControllerDeviceWin32_SecurityDescriptorWin32_SecuritySettingWin32_SecuritySettingAccessWin32_SecuritySettingAuditingWin32_SecuritySettingGroupWin32_SecuritySettingOfLogicalFileWin32_SecuritySettingOfLogicalShareWin32_SecuritySettingOfObjectWin32_SecuritySettingOwnerWin32_SelfRegModuleActionWin32_SerialPortWin32_SerialPortConfigurationWin32_SerialPortSettingWin32_ServiceWin32_ServiceControlWin32_ServiceSpecificationWin32_ServiceSpecificationServiceWin32_SettingCheckWin32_ShareWin32_ShareToDirectoryWin32_ShortcutActionWin32_ShortcutFileWin32_ShortcutSAPWin32_SIDWin32_SMBIOSMemoryWin32_SoftwareElementWin32_SoftwareElementActionWin32_SoftwareElementCheckWin32_SoftwareElementConditionWin32_SoftwareElementResourceWin32_SoftwareFeatureWin32_SoftwareFeatureActionWin32_SoftwareFeatureCheckWin32_SoftwareFeatureParentWin32_SoftwareFeatureSoftwareElementsWin32_SoundDeviceWin32_StartupCommandWin32_SubDirectoryWin32_SystemAccountWin32_SystemBIOSWin32_SystemBootConfigurationWin32_SystemDesktopWin32_SystemDevicesWin32_SystemDriverWin32_SystemDriverPNPEntityWin32_SystemEnclosureWin32_SystemLoadOrderGroupsWin32_SystemLogicalMemoryConfigurationWin32_SystemMemoryResourceWin32_SystemnetworkConnectionsWin32_SystemOperatingSystemWin32_SystemPartitionsWin32_SystemProcessesWin32_SystemProgramGroupsWin32_SystemResourcesWin32_SystemServicesWin32_SystemSettingWin32_SystemSlotWin32_SystemSystemDriverWin32_SystemTimeZoneWin32_SystemUsersWin32_TapeDriveWin32_TemperatureProbeWin32_ThreadWin32_TimeZoneWin32_TrusteeWin32_TypeLibraryActionWin32_UninterruptiblePowerSupplyWin32_USBControllerWin32_USBControllerDeviceWin32_UserAccountWin32_UserDesktopWin32_VideoConfigurationWin32_VideoControllerWin32_VideoSettingsWin32_VoltageProbeWin32_WMIElementSettingWin32_WMISetting首先,调用ManagementObjectSearcher实例(在本文中的例子里为searcher )中的Get()方法,该方法将会把返回信息填在这个实例中。然后,你所要做的就是处理这个实例searcher中的数据。
foreach (ManagementObject share in searcher.Get()){// Some Codes ...}
每个ManagementObject的对象中都有一些,我们所需要的数据,当然我们可以接着这么处理这些数据:
foreach (PropertyData PC in share.Properties){//some codes ...}
本文中代码的其它部分只是对于ListView控件的一些操作,很简单,就不再详述了!
复制代码
/// <summary>/// 获得CPU编号/// </summary>/// <returns></returns>public string GetCPUID(){ string cpuid = "";ManagementClass mc = new ManagementClass("Win32_Processor");ManagementObjectCollection moc = mc.GetInstances();foreach (ManagementObject mo in moc){ cpuid = mo.Properties["ProcessorId"].Value.ToString();}return cpuid;}////// 获取硬盘序列号 /// ///public string GetDiskSerialNumber() { //这种模式在插入一个U盘后可能会有不同的结果,如插入我的手机时 String HDid = ""; ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { HDid = (string)mo.Properties["Model"].Value;//SerialNumber break;//这名话解决有多个物理盘时产生的问题,只取第一个物理硬盘 } return HDid; /*ManagementClass mc = new ManagementClass("Win32_PhysicalMedia"); ManagementObjectCollection moc = mc.GetInstances(); string str = ""; foreach (ManagementObject mo in moc) { str = mo.Properties["SerialNumber"].Value.ToString(); break; } return str;*/ } /// /// 获取网卡硬件地址 /// ///public string GetMacAddress() { string mac = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { mac = mo["MacAddress"].ToString(); break; } } return mac; } /// /// 获取IP地址 /// ///public string GetIPAddress() { string st = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { //st=mo["IpAddress"].ToString(); System.Array ar; ar = (System.Array)(mo.Properties["IpAddress"].Value); st = ar.GetValue(0).ToString(); break; } } return st; } /// /// 操作系统的登录用户名 /// ///public string GetUserName() { return Environment.UserName; } /// /// 获取计算机名 /// ///public string GetComputerName() { return Environment.MachineName; } /// /// 操作系统类型 /// ///public string GetSystemType() { string st = ""; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { st = mo["SystemType"].ToString(); } return st; } /// /// 物理内存 /// ///public string GetPhysicalMemory() { string st = ""; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { st = mo["TotalPhysicalMemory"].ToString(); } return st; } /// /// 显卡PNPDeviceID /// ///public string GetVideoPNPID() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_VideoController"); foreach (ManagementObject mo in mos.Get()) { st = mo["PNPDeviceID"].ToString(); } return st; } /// /// 声卡PNPDeviceID /// ///public string GetSoundPNPID() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_SoundDevice"); foreach (ManagementObject mo in mos.Get()) { st = mo["PNPDeviceID"].ToString(); } return st; } /// /// CPU版本信息 /// ///public string GetCPUVersion() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_Processor"); foreach (ManagementObject mo in mos.Get()) { st = mo["Version"].ToString(); } return st; } /// /// CPU名称信息 /// ///public string GetCPUName() { string st = ""; ManagementObjectSearcher driveID = new ManagementObjectSearcher("Select * from Win32_Processor"); foreach (ManagementObject mo in driveID.Get()) { st = mo["Name"].ToString(); } return st; } /// /// CPU制造厂商 /// ///public string GetCPUManufacturer() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_Processor"); foreach (ManagementObject mo in mos.Get()) { st = mo["Manufacturer"].ToString(); } return st; } /// /// 主板制造厂商 /// ///public string GetBoardManufacturer() { SelectQuery query = new SelectQuery("Select * from Win32_BaseBoard"); ManagementObjectSearcher mos = new ManagementObjectSearcher(query); ManagementObjectCollection.ManagementObjectEnumerator data = mos.Get().GetEnumerator(); data.MoveNext(); ManagementBaseObject board = data.Current; return board.GetPropertyValue("Manufacturer").ToString(); } /// /// 主板编号 /// ///public string GetBoardID() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard"); foreach (ManagementObject mo in mos.Get()) { st = mo["SerialNumber"].ToString(); } return st; } /// /// 主板型号 /// ///public string GetBoardType() { string st = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("Select * from Win32_BaseBoard"); foreach (ManagementObject mo in mos.Get()) { st = mo["Product"].ToString(); } return st; }
转载于:https://blog.51cto.com/13280492/2157409