随笔 - 3458, 文章 - 0, 评论 - 739, 阅读 - 1188万
  管理

C#获取CPU使用率 - 开源研究系列文章

Posted on   lzhdim  阅读(10686)  评论(0编辑  收藏  举报

       这次想编写一个CPU使用率的小应用,于是就用此例子来记录了这个代码。下面是源码:

复制代码
using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 性能计数器
        /// </summary>
        private PerformanceCounter cpuUsage;

        /// <summary>
        /// 使用率
        /// </summary>
        private float interval;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.TimerCPUUseage.Enabled = true;
            this.button1.Enabled = false;
            this.button2.Enabled = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            cpuUsage.Close();
            this.TimerCPUUseage.Enabled = false;
            this.button1.Enabled = true;
            this.button2.Enabled = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            cpuUsage = new PerformanceCounter("Processor Information", "% Processor Utility", "_Total");

            this.button1_Click(sender, e);
        }

        private void TimerCPUUseage_Tick(object sender, EventArgs e)
        {
            interval = Math.Min(100, cpuUsage.NextValue());
            this.lblTitle.Text = $"CPU: {interval:f1}%";
        }
    }
}
复制代码

       这里记录了C#里获取显示CPU使用率的一个例子,为后面的那个小应用做铺垫吧。

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2009-04-29 穿越防火墙 让远程桌面自由连接
2025年3月3日 星期一 【蛇】己卯月辛未日 乙巳年 二月初四 全国爱耳日
您的IP:18.222.255.180,操作系统:未知操作系统,浏览器:未知浏览器
Copyright (C) 2000-2025 Lzhdim Software All Rights Reserved
点击右上角即可分享
微信分享提示