Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

System Performance Indicator in C#

0.00/5 (No votes)
11 Jul 2009 1  
System Performance Indicator in C# by That That Guy

Introduction

This application has been designed and programmed in C# with GDI+ technology. This application shows the extensive and actual implementation  of GDI+ technology in .NET This will be helpful for students currently in initial stages of .net.

What it does is  it shows the current cpu usage and ram usage. This also shows the no. of hard disk drives and the amount of space acquired on the particular drive.

Now this be going full fledged this application uses.

GDI+: For attractive look and feel. WMI (Windows Management Instrumentation): To get all info about the CPU, RAM ,HDD's, some native windows libraries, and more which will be dealt down under.

Don't worry the code has lot of comments which will help you to the application and it's working very well.

Using the Code

Under this section i'll be explaining all of it what's used? and what does it mean? and what's new in the code? and how I've done it.

The GDI+ Code

//
	 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); }
        }
    //

The above code is written in paint event of the form - all the variables are set ready for g enerating the UI of System Meter.

The WMI Code 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);
            }
        }

Here's is a code block that uses WMI code to get the current RAM usage from the system. Although there are several instances where WMI has been used this is one of them. For incorporating WMI functionality to your code import this namespace.

using System.Management;

Here in this GetPhysicalMemory() method. A ManagementObjectSearcher object is declared which is a class of Management namespace:

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

As you can see a SQL query like statement is passed onto the ManagementObjectSearcher constructor. Where the first parameter root\CIMV2 is the scope where the particular thing needs to be looked upon.. And the second one is a SQL string that's actually how we retrieve details baout the system through WMI. you can try out this like this link. if you're not well accustomed to WMI. Check it out !!! or search msdn. and all after that the object gets an array of ManagementObject which contains the information of the system. Now which looping through the array of ManagementObject objects i take each object and pass it to custom defined method GetTotalRamUsage() and GetFreePhysicalMemory().

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

The Implementation of both of the above methods.

        //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"]);
        }

Now in the first method it accepts a ManagementObject object. To access data from this object, it has an fixed indexers where only fixed strings can be passed. You might have understood my statements. The

          m[TotalVisibleMemorySize]

will return an value of type object which needs to be type casted that's it... and rest you can do the necessary calculations for the percentages.

Importing the Native Libraries

You need to import a native library User32.dll which will enable the you to drag the system meter without the titlebars.

        #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 needs to be imported and its methods ReleaseCapture and SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); needs to be defined. Now put the following code in the mousedown event of the main UI form

        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);
            }
        }

This code will allow to move a borderless form.

Applying Run at Startup Functionality

Now you'll definately need the system meter to startup at system start, so here is the code for it. For running any app on start up, the easiest way to do is just paste the shortcut of the App inside Start > Programs > Startup folder. But how you are you going to do it programmatically? For that a library is needed called as IWshRuntimeLibrary. Add a reference to this library in your project incorporate the following namespace

using System.Runtime.InteropServices;

This will allow you to run COM components in .NET Code from Settings form when OK button is being clicked

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();

An object of WshShellClass class of IWshRuntimeLibrary library is declared. And the rest you can easily understand that I'm creating a shortcut for the application in Startup folder for it to run on system start. Last of all the application also has coloring feature which can be used to used to change the colors of System Meter. Rest of the things - open up the source code every block has comments in it.

Points of Interest

I learned something......somewhat WMI...A bit something other...A piece of else where things....and a couple of that that things

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here