日期:2008-09-28  浏览次数:20490 次

 

ClockControl.cs

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace ClockTime
{
 /// <summary>
 /// ClockControl 的摘要说明。
 /// </summary>
 public class ClockControl:System.Windows.Forms.UserControl

 {
  private DateTime dt;

  public ClockControl()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
   this.ResizeRedraw=true;
   this.Enabled=false;

  }
  public DateTime Time
  {
   set
   {
    Graphics grfx=this.CreateGraphics();
    Pen pn=new Pen(this.BackColor);
    InitializeCoordinates(grfx);
    if(dt.Hour!=value.Hour)
    {
     DrawHourHand(grfx,pn);
    }
    if(dt.Minute!=value.Minute)
    {
     DrawHourHand(grfx,pn);
     DrawMinuteHand(grfx,pn);
 
    }
    if(dt.Second!=value.Second)
    {
     DrawMinuteHand(grfx,pn);
     DrawSecondHand(grfx,pn);
    }
    if(dt.Millisecond!=value.Millisecond)
    {
     DrawSecondHand(grfx,pn);
    }
    dt=value;
    pn=new Pen(ForeColor);
    DrawHourHand(grfx,pn);
    DrawMinuteHand(grfx,pn);
    DrawSecondHand(grfx,pn);
    grfx.Dispose();
   }
   get
   {return dt;
   }
  }
  protected override  void OnPaint(PaintEventArgs e)
  {
   Graphics grfx=e.Graphics;
   Pen pn=new Pen(ForeColor);
   SolidBrush br=new SolidBrush(ForeColor);
   InitializeCoordinates(grfx);
   DrawDots(grfx,br);
   DrawHourHand(grfx,pn);
   DrawSecondHand(grfx,pn);
   DrawMinuteHand(grfx,pn);
  }
  protected virtual void InitializeCoordinates(Graphics grfx)
  {
   if(this.Width==0 || this.Height==0) return;
   grfx.TranslateTransform(this.Width/2,this.Height/2);
   Single fInches=Math.Min(this.Width/grfx.DpiX,this.Height/grfx.DpiY);
   grfx.ScaleTransform(fInches*grfx.DpiX/2000,fInches*grfx.DpiY/2000);

  }
  protected virtual  void  DrawDots(Graphics grfx ,Brush br)
  {
   int i,iSize;
   for(i=0;i<=59;i++)
   {
    if(i%5==0)
    {
     iSize=100;
    }
    else
     iSize=30;
    grfx.FillEllipse(br,0-iSize/2,-900-iSize/2,iSize,iSize);
    grfx.RotateTransform(6);

   }
  }
 protected virtual void  DrawHourHand(Graphics grfx,Pen pn)
  {
   GraphicsState gs=grfx.Save();
   grfx.RotateTransform(360.0F*Time.Hour/12+30.0F*Time.Minute/60);
   grfx.DrawPolygon(pn,new Point[]{new Point(