Wednesday, September 26, 2007

My first .Net app : C# Analog Clock

Finally, my first try on a simple .NET app is done. I created a analog clock widget using C#. I think it's quite challenging for a beginner because it will require simple background of Math, image processing, and 3D graphics programming.

With the mouse hit-test, anti-aliasing graphics and flicker-free double buffering, you couldn't even tell the difference between it and Sidebar gadget. Yet it is in C#, and it reduces the pain to deal with Win32 API directly.


To draw the hour-hand, minute-hand and second-hand needs a little trick.

1) Set the origin of form to center, from left-top (so that following rotation can be taken place)
2) Save the current state
3) Rotate the new graphics objects
4) Draw the second-hand (or any hands) at new origin, new orientation
5) Restore the saved state
6) Rotate the new graphics objects
7) Draw the minute-hand (or any hands left) at new origin, new orientation
8) Reload the identity / Reset the origin and orientation (Restore the saved state seems failed)
9) Rotate the new graphics objects
10) Draw the hour-hand (or any hands left) at new origin, new orientation

Voila!
You can get the source here or get the exe here!

#p/s: thanks for the Fasticon for its free icon provided.

5 comments:

Unknown said...

Nice!
Good Job!

Anonymous said...

Welldone, very good job

Anonymous said...

Good job man, as an Improvement it would be better to use System.Drawing.Brushes.{COLOR} rather than creating a new SolidBrush every second.

Like this, e.Graphics.FillRectangle(System.Drawing.Brushes.Red, -1, -1, 40, 2).

Regards

gary said...

Marcelo Gamba:

Tq for ur suggestion, will improve next time ;)

Unknown said...

Really nice. I'm also looking for sample code to drag & drop the hour hand, do you know how ;)