110,529
社区成员
发帖
与我相关
我的任务
分享
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;
using System.Threading;
namespace TimeThread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int Timecount = 0;//记录倒计时总毫秒数
int isstop = 0;//标示是否启动/暂停的变量,0表示第一次初始化
private void button1_Click(object sender, EventArgs e)
{
if (this.button1.Text == "开始计时" || this.button1.Text == "继续计时")
{
this.button1.Text = "暂停计时";
if (isstop == 0)//第一次执行或者倒计时事件设置发生变化,则重新倒计时
{
Timecount = Convert.ToInt32(txtTotalmm.Text) * 60000;//毫秒
Thread counter = new Thread(Counter);
counter.Start();
Control.CheckForIllegalCrossThreadCalls = false;//放弃捕获对错误线程的调用,否则在线程中无法调用控件名
this.txtTotalmm.ReadOnly = true;
txthour.ForeColor = Color.Black;
txtmm.ForeColor = Color.Black;
txtss.ForeColor = Color.Black;
txtmss.ForeColor = Color.Black;
}
isstop = 1;//启动
}
else
{
this.button1.Text = "继续计时";
//this.timer1.Stop();
isstop = 2;//暂停
}
}
public void Counter()
{
try
{
while (Timecount >= 0)
{
this.txthour.Text = (Timecount / 3600000).ToString();
this.txtmm.Text = ((Timecount / 60000) % 60).ToString();
this.txtss.Text = ((Timecount / 1000) % 60).ToString();
this.txtmss.Text = (Timecount % 1000).ToString();
if (Timecount == 0)
{
txthour.ForeColor = Color.Red;
txtmm.ForeColor = Color.Red;
txtss.ForeColor = Color.Red;
txtmss.ForeColor = Color.Red;
this.txtTotalmm.ReadOnly = false;
this.button1.Text = "开始计时";
isstop = 0;
try
{
Thread currthread = Thread.CurrentThread;
currthread.Abort();// 终止当前进程,会触发ThreadAbortException异常,从而终止进程,所以下面需要捕获该异常才能终止进程
}
catch (ThreadAbortException) { }
}
if (isstop != 2)
Timecount -= 1;
Thread.Sleep(1);
}
}
catch { }//处理异常关闭情况下的异常问题
}
}
}