C#中timer的用法

  • 格式:pdf
  • 大小:82.11 KB
  • 文档页数:2

C#中timer的⽤法

作⽤:

⽤于背景进程中。通过引发Timer事件,Timer控件可以有规律的隔⼀段时间执⾏⼀次代码。也就是,你可以根据你⾃⼰的需要,给Timer控

件设置时间,Timer每隔这段时间,就执⾏⼀次代码。

属性:

Enabled 控制当前Timer控件是否可⽤

timer1.Enabled=false;不可⽤

timer1.Enabled=true;可⽤

Interval 主要是设置timer2_Tick事件的时间,单位为毫秒

timer1.Interval=1000;. 1秒=1000毫秒

Tick事件:

每经过Interval属性指定的时间间隔时发⽣⼀次.

每1⼩时提⽰⽤户,需要休息了

timer1.Interval=3600000;

//3600000毫秒即3600秒,即1⼩时 private void timer1_Tick(object sender,System.EventArgs e)

{

timer1.Enabled=false;

MessageBox.show("需要休息了,开机已经2⼩时了");

timer1.Enabled=true;

//如果不先把timer1设成false,对话框会⼀直弹下去。

}

到9:00提⽰去上厕所,把timer2.Interval=60000;//1分钟

private void timer2_Tick(object sender, System.EventArgs e){

//得到现在的时间

string cesuotime=DateTime.Now.DateTime.Now.ToShortTimeString();

if(cesuotime.equles("9:00")){

timer1.Enabled=false;

MessageBox.show("该去上厕所了");

timer1.Enabled=true;//如果不先把enabled设置成false对话框会⼀直弹下去

}

}

⼀定时间间隔刷新函数 ( 读取上次刷新时间与当前时间差,如果达到指定的时间差隔刷新函数,类似于Windows操作系统的定时屏保 )

timer1.Interval=3000; //指定三秒刷新⼀次

System.DateTime time2 = System.DateTime.Now; //获取当前时间

System.TimeSpan span =time2-time1; //计算与上次执⾏时间的时间差

if (span.Minutes > 5) //这时定时五分钟刷新⼀次,

{

iniFormMain(); //执⾏刷新主界⾯函数

}

//在主界⾯函数 iniFormMain() 中定义时间变量time1为当前时间

//time1 = System.DateTime.Now;

timer1.Start( ); 启动计时器,属性Enabled = true 完全等同于调⽤Start()⽅法

timer1.Stop( ); 关闭计时器, Enable = false完全等同于调⽤Stop()

using System.Windows.Forms;

// namespace

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent(); // 这条语句是IDE⾃动⽣的

timer1.Interval = 1000; // 设置时间间隔为1000ms,默认为100ms

timer1.Start(); // 启动计时器, (默认不启动)

}

private void timer1_Tick(object sender, EventArgs e)

{

if (timer1.Equals(timer2)) // 判断两个Timer是否相同,这语句没什么⽤

;

else

{

timer1.Stop(); //关闭计时器

MessageBox.Show("two timers are not equal.");

Close(); // 最后关闭窗⼝

}

}

}