警告是:创建表单时出错。有关详细信息,请参阅Exception.InnerException。错误是:无法加载计数器名称数据,因为从注册表中读取了无效的索引。
我的代码是:
Imports System
Imports System.Management
Imports System.Diagnostics
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim cpuLoad As Integer = CDec(PerformanceCounter1.NextValue.ToString())
cpuLoad = 100 - cpuLoad
Label1.Text = cpuLoad.ToString() & "%"
On Error Resume Next
ProgressBar1.Value = cpuLoad.ToString
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Timer1.Start()
Label2.Text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "ProcessorNameString", Nothing)
label3.text = My.Computer.Registry.GetValue("HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\SYSTEM\CentralProcessor\0", "~MHz", Nothing) & " Mhz"
End Sub
End Class
答案 0 :(得分:1)
看看this question。我发现了这个,还有更多的例子表明你的问题是由一个或多个损坏的注册表项引起的。 Pablissimo的回答提供了对问题的解释,以及重建这些条目的相关步骤。
单击“开始”,键入cmd右键单击cmd.exe,然后选择“运行方式” 管理员。在提示符下,键入lodctr / r并按ENTER键。
答案 1 :(得分:0)
首先你的cpu计数器在我的电脑上给出一个奇怪的值。“比它高2倍”
我使用的也是性能计数器,但其值与Windows任务管理器中的值几乎相同。
Dim CpuCounter As New PerformanceCounter()
Dim CpuResult As New Integer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
With CpuCounter
.CategoryName = "Processor"
.CounterName = "% Processor Time"
.InstanceName = "_Total"
End With
CpuResult = CpuCounter.NextValue
CpuLabel.Text = CpuResult & "%"
CpuBar.Value = CpuResult
End Sub
另一件事是...... 获取ProcessorNameString和Mhz的代码正在我的计算机上运行..
但你也可以这样使用它。
你需要导入Microsoft.Win32“但当然你已经拥有了那个”
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cpuName As String
Dim cpuFreq As String
Dim regKey As RegistryKey
regKey = Registry.LocalMachine
regKey = regKey.OpenSubKey("HARDWARE\DESCRIPTION\System\CentralProcessor\0", False)
cpuName = regKey.GetValue("ProcessorNameString")
cpuFreq = regKey.GetValue("~MHz")
Label2.Text = cpuName
Label3.Text = cpuFreq & " MHz"
End Sub
如果这不起作用,您也可以使用WMI“ManagementObjectSearcher”。
您需要Imports System.Management
并将参考System.Management添加到您的项目中。
然后您可以在表单加载事件中使用此代码来获取相同的信息
Dim cpuName As String
Dim cpuFreq As String
Try
Dim searcher As New ManagementObjectSearcher( _
"root\CIMV2", _
"SELECT * FROM Win32_Processor")
For Each queryObj As ManagementObject In searcher.Get()
cpuName = queryObj("Name")
cpuFreq = queryObj("CurrentClockSpeed")
Label2.Text = cpuName
Label3.Text = cpuFreq & "MHz"
Next
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try