C#计时器简单使用
实例一:计时器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Timer : Form
{
public Timer()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
System.Timers.Timer t = new System.Timers.Timer();//实例化Timer类
private void btnTimer_Click(object sender, EventArgs e)
{
int intTime = 3000;
t.Interval = intTime;//设置间隔时间,为毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
}
public void theout(object source, System.Timers.ElapsedEventArgs e)
{ //MessageBox.Show 一种消息提示对话框。该对象只有winform程序才有,可设置内容,标题,按钮,图标,按钮焦点等参数
MessageBox.Show(e.SignalTime.ToString(), "标题", MessageBoxButtons.OKCancel, MessageBoxIcon.Question,MessageBoxDefaultButton.Button1);
}
private void btnOpenForm2_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
this.Visible = false;
}
}
}
实例二:倒计时功能
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
int mint = 10;
int scss = 59;
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = mint + "分";
label2.Text = scss + "秒";
this.timer1.Interval = 1000; //设置间隔时间,为毫秒;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);////设置每间隔3000毫秒(3秒)执行一次函数timer1_Tick
this.timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (mint >= 0)
{
scss--;
if (scss == 0)
{
mint--;
label1.Text = mint.ToString() + "分";
scss = 59;
}
label2.Text = scss.ToString() + "秒";
}
}
}
}