11,431,011 members (68,864 online)

# Analog clock control in C#

, 23 Feb 2005 CPOL
 Rate this:
How to make an analog clock control in C#.

## Introduction

This article shows how to create an analog clock control in C# using simple and efficient coding, and such that it adjusts itself whenever resized to new dimensions. There are certain settings to make the control customizable. Being a component, we can add our control to the toolbox, drop it on a form, and draw it to any dimension, it will look fine.

This article is for you if you are new to C# controls but quite familiar with C# and its syntax. It also assumes that you have some basic knowledge of high school mathematics.

## Background

To start with our clock, we need some mathematics. The positions of hands in a clock are specified in polar coordinate system. The minute/hour/second values are nothing but a function of the angular displacement of the hand. Hence, we have to write some code to convert this polar quantity to a rectangular one because C# graphics doesn’t understand polar coordinate system; we have to specify the x and y coordinates of the hand.

We first need to find the values of current time.

```DateTime dateTime = DateTime.Now;
int hour = dateTime.Hour % 12; // also converts 24hrs to 12hrs format
int minute = dateTime.Minute;
int sec = dateTime.Second;```

We have to convert these values to radians. In one complete rotation of a hand, there are 360 degrees (radians) but only 12 hours; so to convert hours to radians, we have to write:

`float hourRadian = hour * 360/12 * PI/180;`

Similarly, as there are 60 minutes (and seconds) for one rotation, we can end up with the following formulae:

```float minRadian = minute * 360/60 * PI/180;
float secRadian = sec * 360/60 * PI/180;```

Now the only thing left is to convert these polar quantities to rectangular ones so that we can draw a line (hand) using x and y coordinates. Let's recall our school mathematics formulae to solve this problem.

```X = r*cos(angle)
Y = r*sin(angle)```

But there is one problem with this: a clock rotates in clock-wise manner while our polar system rotates in anti-clockwise manner; so if we use the above formula directly, the output will be an “image” of the clock (i.e., rotating in anti-clockwise direction). To have this problem solved, let's invert the position of sine and cosine in the above formulae: hence, our code to transform the position of clock hand (its end point) from polar to rectangular system will be:

```float hourEndPointX = lengthofHourHand * System.Math.Sin(hourRadian)
float hourEndPointY = lengthofHourHand * System.Math.Cos(hourRadian)```

Now we’ve done all the transformation, it's time to draw a line from the centre of the clock to the endpoints of the hands. We can do something like:

`Line(centerX, centerY, hourEndPointX, hourEndPointY)`

The above code works fine but this is a digital rather than an analog clock in the sense that hour hand is only updated after one entire hour. For instance, observe your clock when time changes from 9:59 to 10:00, the hour hand moves from 9 to 10 directly. We need to do something such that the hour hand also updates its position after every minute. For this, let us include fraction of minutes in the calculation of hour radians, as follows:

```float hour = dateTime.Hour%12 + (float)dateTime.Minute/60
float hourRadian = hour * 360/12 * PI/180;```

Now convert these polar quantities to rectangular form and draw the hand.

```float hourEndPointX = lengthofHourHand * System.Math.Sin(hourRadian);
float hourEndPointY = lengthofHourHand * System.Math.Cos(hourRadian);
Line(centerX, centerY, hourEndPointX, hourEndPointY);```

In a similar fashion, we can write code for drawing hands of minutes and seconds.

## Creating our control

Now that we have learned the basics of clock implementation, it's time to build our control. Create a new project named "AnalogClockControl". Be sure to select "Windows Control Library" from the Templates.

Select "User Control" from the templates, rename "UserControl1.cs" to "AnalogClock.cs".

Open the design view and drag a timer control from your toolbox on your control. Set its Interval property to 1000, and Enabled property to true. This timer will be used to keep our clock "running", i.e. it will update our clock after every second.

Let's start our coding by declaring the following member variables:

```public class AnalogClock : System.Windows.Forms.UserControl
{
const float PI=3.141592654F;

DateTime dateTime;

float fCenterX;
float fCenterY;

float fHourLength;
float fMinLength;
float fSecLength;

float fHourThickness;
float fMinThickness;
float fSecThickness;

bool bDraw5MinuteTicks=true;
bool bDraw1MinuteTicks=true;
float fTicksThickness=1;

Color hrColor=Color.DarkMagenta ;
Color minColor=Color.Green ;
Color secColor=Color.Red ;
Color circleColor=Color.Red;
Color ticksColor=Color.Black;

...
...```

Whenever our control is loaded, its attributes must be initialized. Our clock should also adjust itself whenever resized to a new value. So add the following code to the `Load` and `Resize` events of our control. In the `Resize` event, I have specified (hard coded) certain values to get a nice look, you can alter these values if you want.

```    private void AnalogClock_Load(object sender, System.EventArgs e)
{
dateTime=DateTime.Now;
this.AnalogClock_Resize(sender,e);
}

private void AnalogClock_Resize(object sender, System.EventArgs e)
{
this.Width = this.Height;
this.fCenterX = this.ClientSize.Width/2;
this.fCenterY = this.ClientSize.Height/2;
this.fHourLength = (float)this.Height/3/1.65F;
this.fMinLength = (float)this.Height/3/1.20F;
this.fSecLength = (float)this.Height/3/1.15F;
this.fHourThickness = (float)this.Height/100;
this.fMinThickness = (float)this.Height/150;
this.fSecThickness = (float)this.Height/200;
this.Refresh();
}```

Our `dateTime` variable should be immediately updated and the clock must be redrawn whenever our timer's `Tick` event is triggered. Double-click `timer1` to go to the `timer1_Tick` event and add the following code:

```    private void timer1_Tick(object sender, System.EventArgs e)
{
this.dateTime=DateTime.Now;
this.Refresh();
}```

Let us write two functions, `DrawLine()` and `DrawPolygon()`, to draw clock hands of specified length, thickness and color, towards a point whose location is given as radians.

```    private void DrawLine(float fThickness, float fLength, Color color,
{
e.Graphics.DrawLine(new Pen( color, fThickness ),
}

private void DrawPolygon(float fThickness, float fLength, Color color,
{

PointF A=new PointF( (float)(fCenterX+
(float)(fCenterY -
PointF B=new PointF( (float)(fCenterX+
(float)(fCenterY -
PointF C=new PointF( (float)(fCenterX+
(float) (fCenterY -
PointF D=new PointF( (float)(fCenterX-
(float)(fCenterY +
PointF[] points={A,D,B,C};
e.Graphics.FillPolygon( new SolidBrush(color), points );
}```

Now we include two more functions, `Start()` and `Stop()`:

```    public void Start()
{
timer1.Enabled=true;
this.Refresh();
}

public void Stop()
{
timer1.Enabled=false;
}```

Our control's `Paint` event will be actually drawing our clock, so we have to write the following code to our control's `Paint` event. This first converts the values of hour, minute and second into radians, and then calls `DrawPolygon()` and `DrawLine()` methods to draw the respective hands. It also draws Ticks for our clock.

```    private void AnalogClock_Paint(object sender,
System.Windows.Forms.PaintEventArgs e)
{

DrawPolygon(this.fHourThickness,
DrawPolygon(this.fMinThickness,
DrawLine(this.fSecThickness,

for(int i=0;i<60;i++)
{
if ( this.bDraw5MinuteTicks==true && i%5==0 )
// Draw 5 minute ticks
{
e.Graphics.DrawLine( new Pen( ticksColor, fTicksThickness ),
fCenterX +
fCenterY -
fCenterX +
fCenterY -
}
else if ( this.bDraw1MinuteTicks==true ) // draw 1 minute ticks
{
e.Graphics.DrawLine( new Pen( ticksColor, fTicksThickness ),
fCenterX +
fCenterY -
fCenterX +
fCenterY -
}
}

//draw circle at center
e.Graphics.FillEllipse( new SolidBrush( circleColor ),
}```

We are done with our clock control, now it's time to include some properties to our control so that the user can change its look.

```   public Color HourHandColor
{
get { return this.hrColor; }
set { this.hrColor=value; }
}

public Color MinuteHandColor
{
get { return this.minColor; }
set { this.minColor=value; }
}

public Color SecondHandColor
{
get { return this.secColor; }
set { this.secColor=value;
this.circleColor=value; }
}

public Color TicksColor
{
get { return this.ticksColor; }
set { this.ticksColor=value; }
}

public bool Draw1MinuteTicks
{
get { return this.bDraw1MinuteTicks; }
set { this.bDraw1MinuteTicks=value; }
}

public bool Draw5MinuteTicks
{
get { return this.bDraw5MinuteTicks; }
set { this.bDraw5MinuteTicks=value; }
}```

It's all done. Compile the control by building the solution. It will create "AnalogClock.dll". This is the file we'll use later on in other projects when we want to use this control.

## Using the control

Once we have successfully build the solution, we can easily use our control in other projects. Here's the method: Select "Add/Remove Items.." from the toolbox popup menu and locate "AnalogClock.dll" using Browse button. Once the control is added to the toolbox, we can simply draw it on our forms and use it like other regular controls. Enjoy.

## History

• Version 1.0.
• Initial version. Needs your suggestions for improvement.

## Share

Software Developer
Pakistan

Syed Mehroz Alam, living in Karachi, Pakistan, is a developer focusing Microsoft technologies. He has completed his bachelors as a Computer Systems Engineer in 2006 and is currently pursuing a Masters degree in Computer Science. He loves to learn, discover and master all aspects of .NET and SQL Server. Mehroz has developed rich internet enterprise applications using Silverlight in addition to the traditional ASP.NET and Windows Forms applications. He has worked with all three components of SQL Business Intelligence Studio: SSIS, SSRS and SSAS for developing BI Solutions and Data warehouse. He loves to write complex TSQL queries and evaluate his skills by participating in various TSQL Challenges. His blog can be viewed at http://smehrozalam.wordpress.com.

 First Prev Next
 code detecting system time for analog clock in turbo c++ Member 1082437716-May-14 19:52 Member 10824377 16-May-14 19:52
 Secound Hand Pouya4725-Nov-12 8:44 Pouya47 25-Nov-12 8:44
 Severe Memory Leaks... Wasia5-Apr-10 11:45 Wasia 5-Apr-10 11:45
 Re: Severe Memory Leaks... xeiura0397422329-Mar-11 8:19 xeiura03974223 29-Mar-11 8:19
 Gee, enough time to suss it out, and diss the coder, but not enough time to show how bright you are with some fixes? Typical. So sad.
 Re: Severe Memory Leaks... Kelanor16-Aug-12 4:25 Kelanor 16-Aug-12 4:25
 Re: Severe Memory Leaks... RickZeeland11-Mar-13 10:40 RickZeeland 11-Mar-13 10:40
 double buffer Harm Salomons28-Mar-10 7:22 Harm Salomons 28-Mar-10 7:22
 Re: double buffer Syed Mehroz Alam4-Apr-10 20:58 Syed Mehroz Alam 4-Apr-10 20:58
 nice! thanks a lot Nitin Sawant11-Dec-09 0:25 Nitin Sawant 11-Dec-09 0:25
 Re: nice! thanks a lot Syed Mehroz Alam15-Dec-09 3:59 Syed Mehroz Alam 15-Dec-09 3:59
 tanx nequee9-Jan-09 12:45 nequee 9-Jan-09 12:45
 tanx nequee9-Jan-09 12:40 nequee 9-Jan-09 12:40
 Re: tanx Syed Mehroz Alam15-Dec-09 3:58 Syed Mehroz Alam 15-Dec-09 3:58
 Nice Work bilal haider21-Nov-08 4:57 bilal haider 21-Nov-08 4:57
 Re: Nice Work Syed Mehroz Alam21-Nov-08 23:17 Syed Mehroz Alam 21-Nov-08 23:17
 VERY helpful. Oxcarz10-Aug-08 14:25 Oxcarz 10-Aug-08 14:25
 Re: VERY helpful. Syed Mehroz Alam10-Aug-08 20:06 Syed Mehroz Alam 10-Aug-08 20:06
 Digital Clock Control Yousef Mannaa3-Apr-07 5:27 Yousef Mannaa 3-Apr-07 5:27
 Simply of use amrelgarhy81@yahoo.com27-Oct-06 17:13 amrelgarhy81@yahoo.com 27-Oct-06 17:13
 VB.Net Version GraGra_339-Jul-05 19:20 GraGra_33 9-Jul-05 19:20
 Did you know Anonymous5-Mar-05 3:06 Anonymous 5-Mar-05 3:06
 Re: Did you know tvcompass7-Mar-05 1:39 tvcompass 7-Mar-05 1:39
 Re: Did you know Syed Mehroz Alam14-Mar-05 21:06 Syed Mehroz Alam 14-Mar-05 21:06
 Using Matrix Transforms npross26-Mar-05 7:02 npross 26-Mar-05 7:02
 Re: Using Matrix Transforms Syed Mehroz Alam5-Apr-05 21:54 Syed Mehroz Alam 5-Apr-05 21:54
 Re: Using Matrix Transforms xeiura0397422329-Mar-11 7:02 xeiura03974223 29-Mar-11 7:02
 Re: Did you know Oxcarz10-Aug-08 14:28 Oxcarz 10-Aug-08 14:28
 Re: Did you know Harm Salomons28-Mar-10 9:21 Harm Salomons 28-Mar-10 9:21
 Last Visit: 31-Dec-99 19:00     Last Update: 4-May-15 1:18 Refresh 1