Introduction
This article introduces how to make a Vista style cool CPUInfo control with C#. This control can get a percentage of CPU and Memory of the current Windows system.
Background
Microsoft provides a beautiful sidebar in the Vista System, so I want to make the same control with C#. Thanks to GDI+, you can find that it is very easy to do so.
Using the Code
The main class is the VistaCPUInfo
class; it is inherited from the Usercontrol
class:
public partial class VistaCPUInfo : UserControl
{
...
}
To get the percentage of CPU, use the following code:
if (pc == null) pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
cpu = (float)pc.NextValue();
To get the percentage of physical memory, use the following code:
[StructLayout(LayoutKind.Sequential)]
public struct MEMORY_INFO
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}
...
MEMORY_INFO MemInfo;
MemInfo = new MEMORY_INFO();
GlobalMemoryStatus(ref MemInfo);
mem = (float)MemInfo.dwMemoryLoad;
Then, use GDI+ methods to draw the result:
void VistaCPUInfo_Paint(object sender, PaintEventArgs e)
{
e.Graphics.TextRenderingHint =
System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
e.Graphics.DrawImage
(Image, (int)positionRect.X, (int)positionRect.Y, 198, 159);
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform
(positionRect.X + 68f, positionRect.Y + 82f);
e.Graphics.RotateTransform(cpuCurAngle);
e.Graphics.DrawImage(ImageDial, -5, -49, 10, 98);
e.Graphics.ResetTransform();
e.Graphics.TranslateTransform
(positionRect.X + 143f, positionRect.Y + 50f);
e.Graphics.RotateTransform(memCurAngle);
e.Graphics.DrawImage(ImageDialSmall, -5, -35, 10, 70);
e.Graphics.ResetTransform();
e.Graphics.DrawImage
(ImageDialDot, (int)positionRect.X, (int)positionRect.Y, 198, 150);
RectangleF rect = new RectangleF((int)positionRect.X + 53,
(int)positionRect.Y + 107, 35, 15);
e.Graphics.DrawString(((int)percentOfCPU).ToString() +
"%", textFont, textBrush, rect, format);
rect = new RectangleF((int)positionRect.X + 127,
(int)positionRect.Y + 66, 35, 13);
e.Graphics.DrawString(((int)percentOfMemory).ToString() +
"%", textFont, textBrush, rect, format);
e.Graphics.DrawImage
(ImageGlass, (int)positionRect.X, (int)positionRect.Y, 198, 159);
}
Points of Interest
- Developing with GDI+ and C# is an very interesting thing!
- PNG format picture is very good for drawing alpha pics!
- For more code samples, please visit this Web site.
History
- 2008/1/8: First posted on cnpopsoft.com
- 2008/5/9: Modified by Davidwu: disabled the animation in designtime mode. (thanks to Johnny J.!)