HreoWinGauge2.0 试用版下载地址:http://download.youkuaiyun.com/source/6896899
(5)使时间指针转动
时、分、秒指针指向的刻度必须与操作系统的时间相对应,且每秒钟更新一次。因此必须使用定时器进行定时刷新。可以使用C#.NET中任意一种定时器,这里使用System.Threading.Timer,请注意它的回调函数在另一个线程中执行,编写程序时应注意数据资源访问冲突和线程重入问题。详细程序如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace HeroWinGaugeSamples
{
publicpartial class Clock : Form
{
private System.Threading.Timer timer;
private HeroWinGauge.CircularPointer hourPointer, minutePointer, secondPointer;
// This delegate enables asynchronous calls for setting
// the text property on a TextBox control.
delegatevoid SetClockCallback();
public Clock()
{
InitializeComponent();
}
privatevoid Clock_Load(object sender,EventArgs e)
{
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(ThreadProc);
// Create a timer that signals the delegate to invoke
// and start timer at once
// null : no parameter send to callback function
timer = new System.Threading.Timer(timerDelegate, null, 0, 1000);
hourPointer = (HeroWinGauge.CircularPointer)gaugeContainer1.GaugeComponents[0].MiddleLayerParts[0];
minutePointer = (HeroWinGauge.CircularPointer)gaugeContainer1.GaugeComponents[0].MiddleLayerParts[1];
secondPointer = (HeroWinGauge.CircularPointer)gaugeContainer1.GaugeComponents[0].MiddleLayerParts[2];
}
// Thread for process data
privatevoid ThreadProc(object patameter) // the parameter is null
{
try
{
// because this function is running in an other thread,and may be called from two thread at the same time
SetClockCallback d = new SetClockCallback(UpdateClock);
//this.Invoke(d, new object[] { text });
this.Invoke(d, null);
}
catch
{
return;
}
}
// show the data
privatevoid UpdateClock()
{
DateTime dt = DateTime.Now;
//set label
string text = dt.ToString("T");
lbDateTime.Text = text;
//set clock control
if(dt.Hour>12)
hourPointer.Value=dt.Hour-12 + (double)dt.Minute / 60;
else
hourPointer.Value = dt.Hour + (double)dt.Minute / 60;
minutePointer.Value = dt.Minute + (double)dt.Second / 60;
secondPointer.Value = dt.Second;
}
privatevoid Clock_FormClosing(object sender,FormClosingEventArgs e)
{
timer.Dispose();
}
}
}
为了与系统时间对照比较,程序中还特别将系统时间显示在一个Label控件中。另外对时、分、秒指针的快速引用方法请参考使用手册中关于“在用户应用程序中如何快速引用对象和属性”一节的说明。
(6)编译运行程序
到此,一个完整的时钟演示程序已全部完成,可以编译运行。运行此程序时,时、分、秒指针将按系统时间转动,完整界面见下图。
图7.6- 7 Clock窗体4