C#中Timer组件应用实例
Timer组件
1.功能
Timer是定期引发事件的组件,该组件是为Windows窗体环境设计的,图1所示为Timer组件。

图1 Timer组件
2.属性
(1)Enable属性。此属性用于指定计时器是否运行,此属性设置为True,则表示可以启动计时器。
语法:
public bool Enabled { get; set; }
属性值:如果Timer引发Elapsed事件,则为True;否则,为False。默认值为False。
(2)Interval属性。获取或设置引发Elapsed事件的间隔。
语法:
public double Interval { get; set; }
属性值:引发Elapsed事件的间隔时间(以ms为单位)。默认值为100ms。
示例
Enabled属性和Interval属性的使用
本示例设置Timer控件的间隔时间和停止控件。
程序主要代码如下:
this.timer1.Interval = 1000;
this.timer1.Enabled = False;
3.事件
Tick事件:该事件在当指定的计时器间隔已过去而且计时器处于启用状态时发生。
语法:
public event EventHandler Tick
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace _8_11
{
static class Program
{
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmPictureBox());
}
}
}
★★★★★frmPictureBox窗体设计文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _8_11
{
public partial class frmPictureBox : Form
{
public frmPictureBox()
{
InitializeComponent();
}
private void frmPictureBox_Load(object sender, EventArgs e)
{
this.pictureBox1.Image = imageList1.Images[0];
this.pictureBox2.Image = imageList1.Images[1];
this.pictureBox1.SizeMode= PictureBoxSizeMode.StretchImage;
this.timer1.Interval = 1000;
this.timer1.Enabled = false;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.timer1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
this.label2.Text = "现在时间为:" + DateTime.Now.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
}
public int i = 0;
private void pictureBox2_Click(object sender, EventArgs e)
{
this.timer2.Enabled = true;
}
private void timer2_Tick_1(object sender, EventArgs e)
{
this.pictureBox2.Image = this.imageList1.Images[i];
i++;
if (i == imageList1.Images.Count - 1)
i = 0;
}
}
}
★★★★★frmPictureBox窗体代码文件完整程序代码★★★★★