<< VB.Net 使用 PerformanceCounter 的写法 >>
Imports System.Diagnostics ' 汇入System.Diagnostics 命名空间
Public Class Form1
' 宣告并建立"效能计数器元件" 类别
' New PerformanceCounter(CategoryName,CounterName,InstanceName)
Private PfmcCounter As New PerformanceCounter("Processor", "% Processor Time", "_Total")
' CategoryName : 取得或设定这个效能计数器的效能计数器分类的名称。
' CounterName : 取得或设定与这个PerformanceCounter 执行个体相关的效能计数器的名称。
' InstanceName : 取得或设定这个效能计数器的执行个体名称。
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Interval = 900 ' Timer.Interval 属性: 取得或设定引发Elapsed 事件的间隔。
Timer1.Enabled = True ' 启动Timer
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' PerformanceCounter.NextValue 方法: 取得计数器样本,并为其传回计算过的值。
Label1.Text = PfmcCounter.NextValue.ToString & " %"
End Sub
End Class
================================================================
<< VB.Net 使用 WMI 的写法 >>
Dim objWMI As Object
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Interval = 500
Timer1.Enabled = True
objWMI = GetObject("winmgmts:")
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick ' Timer 事件
CPU_Usage()
End Sub
Private Sub CPU_Usage() ' 用 WMI 取得 CPU 使用率
Dim strCls, strCPU As String
strCls = "Win32_Processor" ' WMI 类别
strCPU = "CPU0" ' 当有多颗 CPU 时 , 可调整为 CPU1 , CPU2 .. 依此类推
Debug.WriteLine(objWMI.InstancesOf(strCls)(strCls & ".DeviceID=""" & strCPU & """").LoadPercentage) ' 取得使用率
End Sub