65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 中的系统性能指示器

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.27/5 (8投票s)

2009 年 7 月 14 日

CPOL

4分钟阅读

viewsIcon

45443

downloadIcon

1882

C# 中的系统性能指示器(作者:That That Guy)。

引言

此应用程序是用 C# 和 GDI+ 技术设计和编程的。 此应用程序展示了 .NET 中 GDI+ 技术的广泛和实际应用。 这将对目前处于 .net 初级阶段的学生有所帮助。

它所做的是显示当前的 CPU 使用率和 RAM 使用率。 这也显示了硬盘驱动器的数量以及特定驱动器上占用的空间量。

现在这个应用程序将会全面使用。

GDI+:为了美观的外观和感觉。 WMI(Windows Management Instrumentation):获取有关 CPU、RAM、HDD 的所有信息,一些本机 Windows 库,以及更多将在下面处理的内容。

不用担心,代码有很多注释,可以帮助您了解应用程序及其工作原理。

Using the Code

在本节中,我将解释所有使用的内容? 它是什么意思? 代码中的新内容是什么? 以及我是如何完成的。

GDI+ 代码

//
	 private void Form1_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                _grap = e.Graphics;
                //initialising the variables for drawing cpu and ram bars.  
                _cpuPt = new Point(47, 36);
                _cpuSize = new Size(_cpuUnit, 8);
                _ramPt = new Point(47, 55);
                _ramSize = new Size(_ramUnit, 8);
                //code to draw ram and cpu bars
                SolidBrush brush = new SolidBrush(_ramCpuColor);
                _grap.DrawRectangle(new Pen(_ramCpuColor), new Rectangle(_cpuPt, 
                    new Size(100, 8)));
                _grap.FillRectangle(brush, new Rectangle(_cpuPt, _cpuSize));
                _grap.DrawRectangle(new Pen(_ramCpuColor), new Rectangle(_ramPt,
                    new Size(100, 8)));
                _grap.FillRectangle(brush, new Rectangle(_ramPt, _ramSize));
                //calling the method to draw drives
                DrawDrives();
            }
            catch (Exception dd) { MessageBox.Show(dd.Message); }
        }
    //

上面的代码是在窗体的 paint 事件中编写的 - 所有变量都已准备好用于生成 System Meter 的 UI。

WMI 代码 T

   //Uses WMI (Windows Management Instrumentation) to Initialize Variables
   //for System Meter.
        private void GetPhysicalMemory()
        {
            ManagementObjectSearcher mgtObj = new ManagementObjectSearcher(
                "root\\CIMV2", "Select * from Win32_OPeratingSystem");
            foreach (ManagementObject obj in mgtObj.Get())
            {
                _totalRamMemory = GetTotalRamUsage(obj);
                _freePhysicalMemory = GetFreePhysicalMemory(obj);
            }
        }

这是一个代码块,它使用 WMI 代码从系统中获取当前的 RAM 使用情况。 虽然在多个实例中使用了 WMI,但这是其中之一。 要将 WMI 功能合并到您的代码中,请导入此命名空间。

using System.Management;

在此GetPhysicalMemory()方法中。 声明了一个 ManagementObjectSearcher 对象,它是 Management 命名空间的一个类

ManagementObjectSearcher mgtObj = new ManagementObjectSearcher("root\\CIMV2",
    "Select * from Win32_OPeratingSystem");

正如您所见,一个类似于 SQL 查询的语句被传递给 ManagementObjectSearcher 构造函数。 其中第一个参数 root\CIMV2 是需要查找特定内容的作用域。 第二个是一个 SQL 字符串,这实际上是我们通过 WMI 检索系统详细信息的方式。 您可以尝试一下这个链接。 如果您不熟悉 WMI,查看它!!! 或者搜索 msdn。 此后,该对象获得一个 ManagementObject 数组,其中包含系统的信息。 现在,在循环遍历 ManagementObject 对象数组时,我获取每个对象并将其传递给自定义定义的方法GetTotalRamUsage()GetFreePhysicalMemory()

           foreach (ManagementObject obj in mgtObj.Get())
            {
                _totalRamMemory = GetTotalRamUsage(obj);
                _freePhysicalMemory = GetFreePhysicalMemory(obj);
            }

以上两种方法的实现。

        //Method which takes Management Object and returns a Int64 value
        //of total Physical Memory.
        private Int64 GetTotalRamUsage(ManagementObject m)
        {
            return Convert.ToInt64(m["TotalVisibleMemorySize"]);
        }
        //Method which takes Management Object and returns a Int64 value of
        //Free Physical Memory.
        private Int64 GetFreePhysicalMemory(ManagementObject m)
        {
            return Convert.ToInt64(m["FreePhysicalMemory"]);
        }

现在,在第一种方法中,它接受一个 ManagementObject 对象。 要从此对象访问数据,它有一个固定的索引器,只能传递固定的字符串。 您可能已经理解了我的陈述。 这个

          m[TotalVisibleMemorySize]

将返回一个对象类型的值,需要进行类型转换,就是这样......其余的您可以进行必要的百分比计算。

导入本机库

您需要导入一个本机库 User32.dll,这将使您能够拖动没有标题栏的系统计量器。

        #region Importing Win32 DLL's
        //Importing library User32.dll from %windir%\windows\system32\user32.dll
        [DllImport("User32.dll")]
        //method in user32.dll to move a borderless form.
        public static extern bool ReleaseCapture();
        //again importing the same user32.dll....why i don't know
        [DllImport("User32.dll")]
        //method in user32.dll to pass message to the windows when mouse is down
        //over the form.
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        #endregion

需要导入 User32.dll 及其方法ReleaseCaptureSendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);。 现在将以下代码放在主 UI 窗体的 mousedown 事件中

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //if left button of the mouse was clicked to drag.
                ReleaseCapture();
                SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0);
            }
        }

这段代码将允许移动一个无边框的表单。

应用启动时运行功能

现在您肯定需要系统计量器在系统启动时启动,所以这里是它的代码。 要在启动时运行任何应用程序,最简单的方法是将应用程序的快捷方式粘贴到开始 > 程序 > 启动文件夹中。 但是你打算如何以编程方式做到这一点呢? 为此,需要一个名为 IWshRuntimeLibrary 的库。 在您的项目中添加对此库的引用,并包含以下命名空间

using System.Runtime.InteropServices;

这将允许您在单击“确定”按钮时从“设置”窗体中运行 .NET 代码中的 COM 组件

WshShellClass wshShell = new WshShellClass();
IWshRuntimeLibrary.IWshShortcut smShortcut;
smShortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(
    Environment.GetFolderPath(Environment.SpecialFolder.Startup) + "\\SystemMeter.lnk");
smShortcut.TargetPath = Application.ExecutablePath;
smShortcut.Description = "System Meter shortcut";
smShortcut.Save();

声明了 IWshRuntimeLibrary 库的 WshShellClass 类的一个对象。 其余的您可以很容易地理解,我正在为应用程序在“启动”文件夹中创建一个快捷方式,以便它在系统启动时运行。 最后,该应用程序还具有着色功能,可用于更改系统计量器的颜色。 其余的事情 - 打开源代码,每个块都有注释。

关注点

我学到了一些......有点 WMI......还有一些其他的东西......一点其他地方的东西......还有一些那样的东西

© . All rights reserved.