Click here to Skip to main content
15,866,422 members
Articles / Desktop Programming / Windows Forms

A Fast and Performing Gauge

Rate me:
Please Sign up or sign in to vote.
4.95/5 (169 votes)
24 Aug 2012Zlib4 min read 728.2K   36.3K   421   181
This article shows you how to write a performing control using .NET 2.0 and GDI+.

Sample image

Introduction

This code shows you how to build a fast and performing control using C# and .NET 2.0.

I wrote a similar control as an ActiveX once, using C++, ATL, and GDI, and wondered if it is possible to write performing code using .NET and GDI+. I needed it for another project. So I wrote this little control to show that it actually works.

How the Code Works

The code consists of a C# application and a custom control. The custom control really is the interesting part.

Deriving from Control

We derive from Control as this doesn't give us all these properties we don't actually need like a usercontrol would give us, for example.

C#
public partial class AGauge : Control

Dealing with Properties

Hiding, Shadowing Unwanted Properties

Well, there are still properties that show up in the designer that are not necessary. In C#, you can use the new keyword to get rid of them (shadows in VB).

C#
public new Boolean AllowDrop, AutoSize, ForeColor, ImeMode

Overriding Useful Properties

For properties that you want to use but with a different behaviour, you can use the override keyword (if overrideable) to tell the program to call this overridden property instead of the implementation of the base class, which in our case is the implementation in Control.

C#
public override System.Drawing.Color BackColor..
public override System.Drawing.Font Font..
public override System.Windows.Forms.ImageLayout BackgroundImageLayout..

Custom Properties

To be able to further customize the control in the designer, we need to add some properties of our own. For example:

C#
[System.ComponentModel.Browsable(true),
System.ComponentModel.Category("AGauge"),
System.ComponentModel.Description("The value.")]
public Single Value..

The Browsable attribute tells the designer to show the property in the toolbox or not. The Category attribute tells the designer where to show the property if the categorized view is selected, and the Description attribute adds a description to the property that the designer can show in the toolbox.

Events and Delegates

An event can carry additional information that is sent to the "listening" program, e.g., the form's event handler for this event.

Custom Event Arguments

We want the event to carry the number of the range the needle is in (if it changes from being in one range to being in another). To add some data to the event, we derive from the standard event args and add a variable which is initialized in the constructor. This will hold the extra information sent along.

C#
public class ValueInRangeChangedEventArgs : EventArgs
{
 public Int32 valueInRange;
 public ValueInRangeChangedEventArgs(Int32 valueInRange)
 {
  this.valueInRange = valueInRange;
 }
}

Event Delegate

The event handler "listening" for our event needs to be of a type that "understands" our event. With the delegate statement, we define this type.

C#
public delegate void ValueInRangeChangedDelegate(Object sender, 
                     ValueInRangeChangedEventArgs e);

And the Event

C#
[Description("This event is raised if the value falls into a defined range.")]
public event ValueInRangeChangedDelegate ValueInRangeChanged;

The event is of the type we defined in the delegate statement. The Description attribute enables the designer to show a description for the event in the Toolbox.

Constructor

The constructor is called when the control is created, e.g., before it will be shown in the designer. Here, we set the style of the control to enable double buffering. This isn't really necessary since we will do our own double buffering, but it doesn't hurt to do so.

C#
public AGauge()
{
 InitializeComponent();
 SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
}

Overriding Member Functions

We need to override some of the member functions.

First, we override OnPaintBackground to ensure that the background is not painted each time the control is refreshed, this uses too much CPU even if double buffering is enabled. One drawback is that we need to handle the drawing of a background image ourselves, but this isn't too much of a problem.

C#
protected override void OnPaintBackground(PaintEventArgs pevent)
{
}

If the control is resized, we need to refresh it. So we override OnResize.

C#
protected override void OnResize(EventArgs e)
{
  drawGaugeBackground = true;
  Refresh();
}

The global variable "drawGaugeBackground" is set to true to tell the control to completely redraw itself. Refresh forces the control to redraw, or if you like to call OnPaint, under the hood, a Windows message is sent, but this is a different story.

Finally, we need to override OnPaint to show some output to the user.

This is what our control really does, it shows the output to the user. It doesn't handle user input like a scrollbar would do. A scrollbar would override OnMouseMove, OnMouseDown, OnKeyPressed, and so on. OnPaint is the heart of our control.

C#
protected override void OnPaint(PaintEventArgs pe)

OnPaint, which is called every time the control is redrawn, e.g., if the value of the gauge changed, determines if it should completely redraw itself or simply paint the background part with the performant function DrawImage. If the background hasn't changed, it only needs to draw the needle, thus avoiding costly GDI+ functions to be called every time. The background changes, e.g., if a property like a color has changed, or the control is resized, for example.

Conclusion

So it really is possible to write fast and performing controls with GDI+ if we use double buffering and blitting (DrawImage).

If you like VB better than C#, you can search for "SpeedyHMI" on SourceForge, this project I wrote contains this gauge written in VB.

Download, build, run and, enjoy!

License

This article, along with any associated source code and files, is licensed under The zlib/libpng License


Written By
Software Developer (Senior)
Germany Germany
Once upon a time there was a C64.
He was a very friendly bilingual fellow looking like a bread box..
His user could always wake him up in no time and ask him to LOAD "*",8,1
C64's friends in school were called CBM, PET and Schneider.
They were boring to talk to after a while so his user got him a girlfriend called Amiga and a business partner called IBM.
Since vitamins are good, his user also got him an Apple to chew on.
As time went by the C64 and his friends got old and eventually were buried in oblivion.
In good memory his user did light a fire for them with a Sparc.
Since then cloning became very popular and the descendants of the C64's business partner rule the scene of his former user.
The descendants did breed many multilingual children of all sizes and shapes and the C64's former user is living happily with them ever after.

Comments and Discussions

 
GeneralRe: Changing Ranges Pin
A.J.Bauer7-Apr-10 21:19
A.J.Bauer7-Apr-10 21:19 
GeneralRe: Changing Ranges Pin
Juwi_uk8-Apr-10 6:21
Juwi_uk8-Apr-10 6:21 
GeneralRe: Changing Ranges [modified] Pin
A.J.Bauer9-Apr-10 2:58
A.J.Bauer9-Apr-10 2:58 
QuestionHow to set own needle colors? Pin
inflames2k2-Feb-10 3:17
inflames2k2-Feb-10 3:17 
AnswerRe: How to set own needle colors? Pin
A.J.Bauer7-Apr-10 21:28
A.J.Bauer7-Apr-10 21:28 
QuestionHow do I add your controls to my application? [modified] Pin
danicoelho711-Nov-09 23:47
danicoelho711-Nov-09 23:47 
AnswerRe: How do I add your controls to my application? Pin
A.J.Bauer12-Nov-09 10:08
A.J.Bauer12-Nov-09 10:08 
GeneralRe: How do I add your controls to my application? Pin
Rastikan3-May-10 11:29
Rastikan3-May-10 11:29 
GeneralHow do I add your controls to my WEB application? Pin
Member 290552826-Jul-10 23:10
Member 290552826-Jul-10 23:10 
GeneralThanks Pin
candresjimenez10-Mar-09 13:41
candresjimenez10-Mar-09 13:41 
GeneralThanks! Very helpful!! Pin
Ruifeng Zhang2-Feb-09 22:46
Ruifeng Zhang2-Feb-09 22:46 
GeneralVersion for C++ Pin
Dieter6822-Jan-09 3:08
Dieter6822-Jan-09 3:08 
GeneralRe: Version for C++ Pin
A.J.Bauer30-Jan-09 0:39
A.J.Bauer30-Jan-09 0:39 
GeneralGauge Graph Pin
Atul Shriram rane12-Dec-08 0:37
Atul Shriram rane12-Dec-08 0:37 
QuestionWeb Pin
Fradique Lee11-Nov-08 13:58
Fradique Lee11-Nov-08 13:58 
GeneralA gradient into the the range bloc color Pin
zitun15-Oct-08 2:48
zitun15-Oct-08 2:48 
Generalsome bugs Pin
Martin Radu14-Sep-08 0:49
Martin Radu14-Sep-08 0:49 
GeneralGood job!!! Pin
Martin Radu12-Sep-08 0:12
Martin Radu12-Sep-08 0:12 
GeneralExcellent Control and Article Pin
Steven A. Lowe16-Aug-08 11:22
Steven A. Lowe16-Aug-08 11:22 
GeneralRe: Excellent Control and Article Pin
Steven A. Lowe6-Sep-08 17:21
Steven A. Lowe6-Sep-08 17:21 
GeneralRe: Excellent Control and Article Pin
A.J.Bauer7-Sep-08 2:04
A.J.Bauer7-Sep-08 2:04 
GeneralC++ Version Pin
JimmyO7-Aug-08 21:09
JimmyO7-Aug-08 21:09 
Generalcopy to clipboard in context menu Pin
JulienV21-Apr-08 20:58
JulienV21-Apr-08 20:58 
GeneralRe: copy to clipboard in context menu Pin
A.J.Bauer22-Apr-08 21:37
A.J.Bauer22-Apr-08 21:37 
Hi Julien,

I'm sure there is people who would like to have this feature for the gauge.
Why not write a small article and put a link here?
I would definitely like to take a look at the code, thank you for your work. Smile | :)

A.J.

Don't Panic, debug it!

QuestionNice efforts, but have some issues with tweaking the gauge Pin
Salam Y. ELIAS17-Apr-08 9:27
professionalSalam Y. ELIAS17-Apr-08 9:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.