亲宝软件园·资讯

展开

C#计时器记录时间 C#实现多个计时器记录不同定时时间

风无痕丶 人气:0

1.定义Timer类、定义委托

//定义Timer类
System.Threading.Timer t3,t1,t2,t4;
//定义委托
public delegate void SetControlValue(object value);

2.初始化

private void InitTimer()//初始化
    {
      
      t1= new System.Threading.Timer(new TimerCallback(T1), null, Timeout.Infinite, 1000);
      t2 = new System.Threading.Timer(new TimerCallback(T2), null, Timeout.Infinite, 1000);
      t3 = new System.Threading.Timer(new TimerCallback(T3), null, Timeout.Infinite, 1000);
      t4 = new System.Threading.Timer(new TimerCallback(T4), null, Timeout.Infinite, 1000);
 }

3.因为要实现定时时间的不同,所以要定义不同的整型变量时、分、秒:

//一号机
int hour = 0;
int minute = 0;
int second = 0;
//二号机
int hour2 = 0;
int minute2 = 0;
int second2 = 0;
//三号机
int hour3 = 0;
int minute3 = 0;
int second3 = 0;
//四号机
int hour4 = 0;
int minute4 = 0;
int second4 = 0;

4.时间执行方法并输出:

private void T4(object state)// 时间T方法
    {

      try
      {
        second4++;
        if (second4 == 60)
        {
          minute4++;
          second4 = 0;
        }
        if (minute4 == 60)
        {
          hour4++;
          minute4 = 0;
        }
        this.Invoke(new SetControlValue(S4), second4);
        this.Invoke(new SetControlValue(S4), minute4);
        this.Invoke(new SetControlValue(S4), hour4);
      }
      catch
      {

      }
    }

    private void S4(object value)
    {
      textBox4.Text = hour4.ToString() + "时" + minute4.ToString() + "分" + second4.ToString() + "秒";
    }

    private void T2(object state)
    {
      try
      {
        second2++;
        if (second2 == 60)
        {
          minute2++;
          second2 = 0;
        }
        if (minute2 == 60)
        {
          hour2++;
          minute2 = 0;
        }
        this.Invoke(new SetControlValue(S2), second2);
        this.Invoke(new SetControlValue(S2), minute2);
        this.Invoke(new SetControlValue(S2), hour2);
      }
      catch
      {

      }
    }
    private void S2(object value)
    {
      textBox2.Text = hour2.ToString() + "时" + minute2.ToString() + "分" + second2.ToString() + "秒";
 }

5.定时器的执行和停止,分别用{你定义的.Change(0, 1000)}、{你定义的.Change(0, 1000)}表示,如:

t1.Change(0, 1000);
t1.Change(Timeout.Infinite, 1000);

6.效果图:

加载全部内容

相关教程
猜你喜欢
用户评论