A fast and performing gauge

来源:百度文库 编辑:神马文学网 时间:2024/07/02 18:33:42
A fast and performing gauge
ByA.J.Bauer.
This article shows you how to write a performing control using .NET 2.0 and GDI+.
C# (C# 2.0)
Windows, .NET (.NET 2.0)
Win32, VS (VS2005), GDI+, WinForms
Dev
Posted: 8 Feb 2007
Views: 2,376
Search   Articles Authors   Advanced Search
Sitemap |Add to IE Search
PrintBroken Article?BookmarkDiscussSend to a friend
32 votes for this article.
Popularity: 7.27. Rating: 4.83 out of 5.
Download source code - 89.9 Kb

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.
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).
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.
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. E.g.,
[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.
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.
public delegate void ValueInRangeChangedDelegate(Object sender, ValueInRangeChangedEventArgs e); And the event
[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.
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.
protected override void OnPaintBackground(PaintEventArgs pevent) { }
If the control is resized, we need to refresh it. So we override OnResize.
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.
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!
About A.J.Bauer

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. Clickhere to view A.J.Bauer‘s online profile.
Other popular C# Controls articles:
Themed Windows XP style Explorer Bar A fully customizable Windows XP style Explorer Bar that supports Windows XP themes and animated expand/collapse with transparency.
XPTable - .NET ListView meets Java‘s JTable A fully customisable ListView style control based on Java‘s JTable.
SourceGrid - Open Source C# Grid Control SourceGrid is a free open source grid control. Supports virtual grid, custom cells and editors, advanced formatting options and many others features
TaskbarNotifier, a skinnable MSN Messenger-like popup in C# and now in VB.NET too The TaskbarNotifier class allows to display an MSN Messenger-like animated popup with a skinned background
[Top] Rate this Article for us!     PoorExcellent


FAQ  Message score threshold 1.0 2.0 3.0 4.0 5.0    Search comments
View Normal (slow) Preview (slow) Message View Topic View Thread View Expanded (Supporters only)    Per page 10 25 50
New Message Msgs 1 to 18 of 18 (Total: 18) (Refresh) First Prev Next
Subject  Author  Date

 caption  varadii  4hrs 6mins ago
  how caption is supposed to work (autochange the text on range change) ?
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Should be usable for ASP.NET, too?!?  Uwe Keim  8hrs 26mins ago
  When extracting your core drawing methods into an image-generating method, and wrapping it up a little bit, it should be convertable into a great Web UserControl, too.
Or is there some general limitation that would hinder that?
--
Try our Windows-based CMS:www.zeta-producer.com
Try our ticket helpdesk system:www.zeta-helpdesk.com
See me working:www.magerquark.com
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Should be usable for ASP.NET, too?!?  Manuel Meza  7hrs 35mins ago
  Where should i start so i can make something like this, y need some gauge controls to show in a web page, and i don‘t want to use flash or something like that, any help?
thanks!
great job again
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Should be usable for ASP.NET, too?!?  Uwe Keim  7hrs 23mins ago
  If you require it in short time and professional, try looking at "Dundas Gauge" (or how they call it).www.dundas.com [^].
--
Try our Windows-based CMS:www.zeta-producer.com
Try our ticket helpdesk system:www.zeta-helpdesk.com
See me working:www.magerquark.com
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Should be usable for ASP.NET, too?!?  A.J.Bauer  5hrs 53mins ago
  This little thing is aiming for applications that update values very quickly, like every 50-100 [ms]. The goal was to save CPU for this sort of App.
Well System.Drawing.Image has a member called "save" that you could use to stream the graphics with. If I got the time I‘ll dive more into ASP, i only know the basics yet.
I would be happy if someone would shows us how to do it in the meantime
Regards
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Can i use this for work?  dvazriel  12hrs 34mins ago
  DUDE YOUR THE BEST. this is exactly what i need, but i was wondering can i use your control for a job related application?
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Can i use this for work?  A.J.Bauer  6hrs 17mins ago
  The code is under z-lib license:
Basically it says, you can whatever you want with hit but don‘t blame me if something goes wrong.
Here is the link to the Open Source Initiative:
http://www.opensource.org/licenses/zlib-license.php[^]
Regards
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Unhandled Exception  Husam Burhan  17hrs 33mins ago
  when I executed the program the following exception appeared:
"Parameter is not valid."
at the statement:
b = new Bitmap((Int32)(boundingBox.Width), (Int32)(boundingBox.Height));
the reason is that both of boundingBox properties (Width and Height) is equal to zero. so I reviewed the previous statement:
boundingBox = g.MeasureString("0123456789", Font, -1, StringFormat.GenericTypographic);
and found that the error was from it. when I changed the value -1 to any value like (100), everything goes well.
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Unhandled Exception  A.J.Bauer  6hrs 22mins ago
  I didn‘t do too much of error handling, i leave this up to the reader.
However if I got time I‘ll check for this, thanks for reporting.
Regards
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Hiding Unwanted Properties  Doug K. Wilson  20hrs 47mins ago
  I like your technique for hiding unwanted properties from the designer. I wish you could also hide them from Intellisense.
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Hiding Unwanted Properties  A.J.Bauer  18hrs 47mins ago
  I didn‘t find anything yet to do this but didn‘t really look much either, I figure it‘s good enough like this for now. If you however find a way to do this please let me know about it.
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Hiding Unwanted Properties  Eric Woodruff  16hrs 47mins ago
  Add the following attributes to properties that you want to hide. The first stops it from showing up in the property grid and the second prevents it from showing up in Intellisense. You can add the third if you also don‘t want its value serialized to the InitializeComponent method of forms that use the control if it differs from the default value.
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
Eric
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 good job, can it run on asp.net?  margiex  23hrs 21mins ago
  thanks.
[Reply |Email |View Thread |Get Link] Score: 1.0 (1 vote). Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: good job, can it run on asp.net?  Manuel Meza  20hrs 55mins ago
  Great job!! i need something like this, but for ASP .NET, any hint?
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: good job, can it run on asp.net?  A.J.Bauer  18hrs 54mins ago
  I‘m not too much into ASP.NET but it‘s on my list of things to pursue. There should be information on MSDN maybe the control needs to derive from WebControl or something like it. If you find it out please let me know.
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse


 Bravo  ferox3000  23hrs 32mins ago
  I have tried several times over the years to create guages that didn‘t rely on saved images and only used GDI and I have never come close to something this nice.
Well done!
Mike
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Bravo  Michal Brylka  21hrs 38mins ago
  I agree, very well done. Finally Dundas has competition
Micha? Bry?ka
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

 Re: Bravo  A.J.Bauer  18hrs 59mins ago
  Thanks
A.J.
Don‘t Panic, debug it!
[Reply |Email |View Thread |Get Link] Rate this message:12345 (out of 5)
Report asSpam orAbuse

Last Visit: 8:47 Friday 9th February, 2007 First Prev Next
General comment   News / Info   Question   Answer   Joke / Game   Admin message