12,952,124 members (57,859 online)
alternative version

#### Stats

252.3K views
94 bookmarked
Posted 15 Feb 2005

# 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.

## You may also be interested in...

 Pro

 View All Threads First Prev Next
 nice! thanks a lot Nitin Sawant10-Dec-09 23:25 Nitin Sawant 10-Dec-09 23:25
 Re: nice! thanks a lot Syed Mehroz Alam15-Dec-09 2:59 Syed Mehroz Alam 15-Dec-09 2:59
 Last Visit: 31-Dec-99 18:00     Last Update: 26-May-17 15:13 Refresh 1