一、前期准备
1、创建一个WindowsApplication
2、放一个Timer控件
二、代码部分
//
定义秒针,分针,时针的长度
private const int s_pinlen = 150 ;
private const int m_pinlen = 100 ;
private const int h_pinlen = 50 ;
private void MyDrawClock( int h, int m, int s)
... {
Graphics g = this.CreateGraphics();
//清除所有
g.Clear(Color.White);
//创建Pen
Pen myPen = new Pen(Color.Black, 1);
//绘制表盘
g.DrawEllipse(myPen, this.ClientRectangle);
//表中心点
Point centerPoint = new Point(this.ClientRectangle.Width / 2, this.ClientRectangle.Height / 2);
//计算出秒针,分针,时针的另外端点
Point secPoint = new Point((int)(centerPoint.X + (Math.Sin(6 * s * Math.PI / 180)) * s_pinlen),
(int)(centerPoint.Y - (Math.Cos(6 * s * Math.PI / 180)) * s_pinlen));
Point minPoint = new Point((int)(centerPoint.X + (Math.Sin(6 * m * Math.PI / 180)) * m_pinlen),
(int)(centerPoint.Y - (Math.Cos(6 * m * Math.PI / 180)) * m_pinlen));
Point hourPoint = new Point((int)(centerPoint.X + (Math.Sin(((30 * h) + (m / 2)) * Math.PI / 180)) * h_pinlen),
(int)(centerPoint.Y - (Math.Cos(((30 * h) + (m / 2)) * Math.PI / 180)) * h_pinlen));
//以不同的颜色绘制
g.DrawLine(myPen, centerPoint, secPoint);
myPen = new Pen(Color.Blue, 2);
g.DrawLine(myPen, centerPoint, minPoint);
myPen = new Pen(Color.Red, 4);
g.DrawLine(myPen, centerPoint, hourPoint);
}
private void timer1_Tick( object sender, EventArgs e)
... {
//得到当前的时、分、秒
int h = DateTime.Now.Hour;
int m = DateTime.Now.Minute;
int s = DateTime.Now.Second;
//调用MyDrawClock绘制图形表盘
MyDrawClock(h, m, s);
//在窗体标题上显示数字时钟
this.Text = String.Format("{0}:{1}:{2}", h, m, s);
}
private const int s_pinlen = 150 ;
private const int m_pinlen = 100 ;
private const int h_pinlen = 50 ;
private void MyDrawClock( int h, int m, int s)
... {
Graphics g = this.CreateGraphics();
//清除所有
g.Clear(Color.White);
//创建Pen
Pen myPen = new Pen(Color.Black, 1);
//绘制表盘
g.DrawEllipse(myPen, this.ClientRectangle);
//表中心点
Point centerPoint = new Point(this.ClientRectangle.Width / 2, this.ClientRectangle.Height / 2);
//计算出秒针,分针,时针的另外端点
Point secPoint = new Point((int)(centerPoint.X + (Math.Sin(6 * s * Math.PI / 180)) * s_pinlen),
(int)(centerPoint.Y - (Math.Cos(6 * s * Math.PI / 180)) * s_pinlen));
Point minPoint = new Point((int)(centerPoint.X + (Math.Sin(6 * m * Math.PI / 180)) * m_pinlen),
(int)(centerPoint.Y - (Math.Cos(6 * m * Math.PI / 180)) * m_pinlen));
Point hourPoint = new Point((int)(centerPoint.X + (Math.Sin(((30 * h) + (m / 2)) * Math.PI / 180)) * h_pinlen),
(int)(centerPoint.Y - (Math.Cos(((30 * h) + (m / 2)) * Math.PI / 180)) * h_pinlen));
//以不同的颜色绘制
g.DrawLine(myPen, centerPoint, secPoint);
myPen = new Pen(Color.Blue, 2);
g.DrawLine(myPen, centerPoint, minPoint);
myPen = new Pen(Color.Red, 4);
g.DrawLine(myPen, centerPoint, hourPoint);
}
private void timer1_Tick( object sender, EventArgs e)
... {
//得到当前的时、分、秒
int h = DateTime.Now.Hour;
int m = DateTime.Now.Minute;
int s = DateTime.Now.Second;
//调用MyDrawClock绘制图形表盘
MyDrawClock(h, m, s);
//在窗体标题上显示数字时钟
this.Text = String.Format("{0}:{1}:{2}", h, m, s);
}
这样一个简易时钟窗体程序就完成了