- 1 year ago
How to Get Current CPU Usage Like Task Manager - Vb.net
To get the current CPU usage in VB.NET, you can use the PerformanceCounter
class from the System.Diagnostics
namespace. This class allows you to access performance counters, including CPU usage. Here's a simple example to get the current CPU usage in percentage:
vb.netImports System.Diagnostics
Public Class Form1
Private cpuCounter As PerformanceCounter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Initialize the PerformanceCounter for CPU Usage
cpuCounter = New PerformanceCounter("Processor", "% Processor Time", "_Total")
cpuCounter.NextValue() ' Call NextValue once to get valid data on the first reading
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
' Get the current CPU usage in percentage
Dim cpuUsage As Integer = CInt(cpuCounter.NextValue())
' Update the label to display CPU usage
Label1.Text = $"CPU Usage: {cpuUsage}%"
End Sub
End Class
In this example, a PerformanceCounter
object is created to monitor the "% Processor Time" performance counter under the "Processor" category for the "_Total" instance (which represents the total CPU usage of the system). The NextValue()
method is called once to get valid data on the first reading, as the first reading is always 0.
Then, a timer is used to periodically retrieve the current CPU usage from the PerformanceCounter
and update the label to display the CPU usage.
Note that the actual CPU usage may fluctuate frequently, so it's essential to update the value periodically using a timer or any other suitable mechanism to get a near-real-time view of the CPU usage.