Click here to Skip to main content
Click here to Skip to main content

Seven-segment LED Control for .NET

By , 2 Jul 2009
 

Introduction

I'm usually not a big fan of custom controls except in the most extreme circumstances. From the point of view of usability, it should always make the most sense to use the controls that are shipped with the Operating System. Your user base is already familiar with the OS's native controls, so creating custom controls would only add to the learning curve for your application. But I digress. Sometimes, there are certain controls that just beg to be written, whether they're useful or not.

That's why I decided to write this seven-segment LED control: not because it's any more "useful" than a standard Label control, but because it looks freakin' sweet. I also wrote the control to become more familiar with the internals of C# and .NET in general. And, if you like the control and are able to use it, or learn from it, so much the better.

Background

Even if you haven't heard the name "seven-segment display" before, you've probably seen quite a few in your lifetime. They appear on pretty much every piece of electronic equipment that needs to display numbers for any reason, like the timer on a microwave oven, the display on a CD player, or the time on your digital wristwatch.

They're called seven-segment displays because they're actually made up of seven "segments" — seven individual lights (LEDs or otherwise) that light up in different patterns that represent any of the ten digits (0 - 9).

Using the code

This custom control can be built into your application by simply including the "SevenSegment.cs" file in your project. Rebuild your project, and you'll be able to select the SevenSegment control from your tool palette and drop it right onto your forms.

To replicate the look of a seven-segment display, I draw seven polygons that precisely match the physical layout of a real display. To model the polygons, I drew them out on graph paper, and recorded the coordinates of each point in each polygon. To draw the polygons on the control, I use the FillPolygon function, passing it the array of points that represent the polygon. Let's examine the control's Paint event to see exactly what's going on:

private void SevenSegment_Paint(object sender, PaintEventArgs e)
{
    //this will be the bit pattern that gets shown on the segments,
    //bits 0 through 6 corresponding to each segment.
    int useValue = customPattern;
    
    //create brushes that represent the lit 
    //and unlit states of the segments
    Brush brushLight = new SolidBrush(colorLight);
    Brush brushDark = new SolidBrush(colorDark);

    //Define transformation for our container...
    RectangleF srcRect = new RectangleF(0.0F, 0.0F, 
                             gridWidth, gridHeight);
    RectangleF destRect = new RectangleF(Padding.Left, Padding.Top, 
                          this.Width - Padding.Left - Padding.Right, 
                          this.Height - Padding.Top - Padding.Bottom);
    
    //Begin graphics container that remaps 
    //coordinates for our convenience
    GraphicsContainer containerState = 
      e.Graphics.BeginContainer(destRect, srcRect, 
                                GraphicsUnit.Pixel);

    //apply a shear transformation based on our "italics" coefficient
    Matrix trans = new Matrix();
    trans.Shear(italicFactor, 0.0F);
    e.Graphics.Transform = trans;

    //apply antialiasing
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    e.Graphics.PixelOffsetMode = PixelOffsetMode.Default;

    // Draw elements based on whether the corresponding bit is high!
    // "segPoints" is a 2D array of points that
    // contains the segment coordinates to draw
    e.Graphics.FillPolygon((useValue & 0x1) == 0x1 ? 
                            brushLight : brushDark, segPoints[0]);
    e.Graphics.FillPolygon((useValue & 0x2) == 0x2 ? 
                            brushLight : brushDark, segPoints[1]);
    e.Graphics.FillPolygon((useValue & 0x4) == 0x4 ? 
                            brushLight : brushDark, segPoints[2]);
    e.Graphics.FillPolygon((useValue & 0x8) == 0x8 ? 
                            brushLight : brushDark, segPoints[3]);
    e.Graphics.FillPolygon((useValue & 0x10) == 0x10 ? 
                            brushLight : brushDark, segPoints[4]);
    e.Graphics.FillPolygon((useValue & 0x20) == 0x20 ? 
                            brushLight : brushDark, segPoints[5]);
    e.Graphics.FillPolygon((useValue & 0x40) == 0x40 ? 
                            brushLight : brushDark, segPoints[6]);

    //draw the decimal point, if it's enabled
    if (showDot)
        e.Graphics.FillEllipse(dotOn ? brushLight : brushDark, 
          gridWidth - 1, gridHeight - elementWidth + 1, 
          elementWidth, elementWidth);

    //finished with coordinate container
    e.Graphics.EndContainer(containerState);
}

You can set the value displayed in the control through two properties: Value and CustomPattern. The Value property is a string value that can be set to a single character such as "5" or "A". The character will be automatically translated into the seven-segment bit pattern that looks like the specified character.

If you want to display a custom pattern that may or may not look like any letter or number, you can use the CustomPattern property and set it to any value from 0 to 127, which gives you full control over each segment, since bits 0 to 6 control the state of each of the corresponding segments.

The way it's done in the code is as follows. I have an enumeration that encodes all the predefined values that represent digits and letters displayable on seven segments:

public enum ValuePattern
{
    None = 0x0, Zero = 0x77, One = 0x24, Two = 0x5D, Three = 0x6D,
    Four = 0x2E, Five = 0x6B, Six = 0x7B, Seven = 0x25,
    Eight = 0x7F, Nine = 0x6F, A = 0x3F, B = 0x7A, C = 0x53,
    D = 0x7C, E = 0x5B, F = 0x1B, G = 0x73, H = 0x3E,
    J = 0x74, L = 0x52, N = 0x38, O = 0x78, 
    P = 0x1F, Q = 0x2F, R = 0x18,
    T = 0x5A, U = 0x76, Y = 0x6E,
    Dash = 0x8, Equals = 0x48
}

Notice that each value is a bit map, with each bit corresponding to one of the seven segments. Now, in the setter of the Value property, I compare the given character against our known values, and use the corresponding enumeration as the currently displayed bit pattern:

//is it a digit?
int tempValue = Convert.ToInt32(value);
switch (tempValue)
{
    case 0: customPattern = (int)ValuePattern.Zero; break;
    case 1: customPattern = (int)ValuePattern.One; break;
    ...
}
...
//is it a letter?
string tempString = Convert.ToString(value);
switch (tempString.ToLower()[0])
{
    case 'a': customPattern = (int)ValuePattern.A; break;
    case 'b': customPattern = (int)ValuePattern.B; break;
    ...
}

Either way, the bit pattern to be displayed in the control ends up in the customPattern variable, which is then used in the Paint event as shown above.

You can also "italicize" the display by manipulating the ItalicFactor property. This value is simply a shear factor that gets applied when drawing the control, as seen in the Paint event. An italic factor of -0.1 makes the display look just slightly slanted, and a whole lot more professional.

If you begin noticing that the segments are being drawn outside the boundary of the control (perhaps from too much italicizing), you can use the Padding property and increase the left/right/top/bottom padding until all of the shapes are within the control's client rectangle.

The control has several other convenient properties for you to play with, such as the background color, the enabled and disabled color for the segments, and the thickness of the segments.

Seven-segment array

In addition to the seven-segment control itself, I'm throwing in another control which is an array of seven-segment displays. This allows you to display entire strings on an array of 7-seg displays. Check out the demo application, and dig around the source code to see how it's used; it's really simple.

To use the array control, include the "SevenSegmentArray.cs" file in your project and rebuild. You'll then be able to select the SevenSegmentArray control from the tool palette.

This control has an ArrayCount property that specifies the number of 7-seg displays in the array, as well as a Value property that takes any string to be displayed on the array. Easy, right?

Points of interest

I must say I had a lot of fun writing this control, and .NET helped put a lot of the fun into it by making it incredibly easy to draw your own shapes, transform coordinates, and introduce truly powerful properties.

Also, coming from somewhat of an electronics background, for me, seeing this control brings a certain nostalgia for simpler times. I hope you enjoy it.

History

  • Minor update: July 2 2009.
  • First revision: June 30 2009.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Dmitry Brant
Software Developer (Senior)
United States United States
Member
Software Engineer and data recovery specialist living in Cleveland, OH.

Author of DiskDigger, a free and easy-to-use recovery and undelete utility.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Generalcommentmembershe105he16 Apr '13 - 21:52 
GeneralGreat ControlmemberRoj16 Mar '13 - 15:46 
QuestionCan your Seven-segment LED Control for .NET be used in WPF?memberTAN THIAM HUAT28 Jan '13 - 15:25 
SuggestionRe: Can your Seven-segment LED Control for .NET be used in WPF?memberRoj16 Mar '13 - 15:30 
GeneralMy vote of 5member2anyone11119 Jun '12 - 15:40 
QuestionAwesome!memberRavi Bhavnani10 Jun '12 - 15:07 
QuestionnicememberCIDev25 Jan '12 - 2:38 
GeneralMy vote of 4memberArif_Madi9 Nov '11 - 19:52 
GeneralMy vote of 4memberRhuros16 May '11 - 21:25 
Generalmy vote of 5memberMaximus Byamukama28 Jan '11 - 6:55 
GeneralJust what I was looking for....memberaspify7 Jan '11 - 20:59 
GeneralMy vote of 5memberDiamonddrake21 Dec '10 - 22:52 
GeneralChange Color by comboBoxmemberchuh6914 Dec '10 - 9:08 
AnswerRe: Change Color by comboBoxmemberJOAT-MON15 Dec '10 - 10:45 
GeneralRe: Change Color by comboBoxmemberchuh6915 Dec '10 - 22:20 
GeneralRe: Change Color by comboBoxmemberJOAT-MON16 Dec '10 - 8:37 
QuestionVery nice - problem with resize?memberwbp4722 Nov '10 - 12:38 
AnswerRe: Very nice - problem with resize?memberwbp4722 Nov '10 - 12:53 
GeneralRe: Very nice - problem with resize?memberAlessandro29 Nov '10 - 1:01 
GeneralNice job!memberant-damage30 Jun '10 - 4:00 
GeneralValuePaternmemberMember 141083123 Jul '09 - 20:41 
GeneralRe: ValuePaternmemberidan_bismut30 Oct '09 - 6:34 
GeneralAnother onememberoruam786 Jul '09 - 15:10 
GeneralWell donememberAlexander_Ukhov2 Jul '09 - 19:09 
QuestionCould you add a colon?memberhoasidpfuaokjsñeirf2 Jul '09 - 12:22 
AnswerRe: Could you add a colon?memberDmitry Brant15 Jul '09 - 5:17 
GeneralRe: Could you add a colon?memberhotspace19 Aug '09 - 10:31 
GeneralCool..memberMd. Marufuzzaman1 Jul '09 - 22:56 
GeneralNice controlmembermarco_ragogna1 Jul '09 - 22:29 
GeneralRe: Nice controlmemberMd. Marufuzzaman1 Jul '09 - 22:59 
GeneralRe: Nice controlmemberDmitry Brant15 Jul '09 - 5:14 
GeneralVery nicememberColin Eberhardt1 Jul '09 - 18:39 
GeneralRe: Very nicememberPawel Gielmuda1 Jul '09 - 23:26 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 2 Jul 2009
Article Copyright 2009 by Dmitry Brant
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid