您的位置:首页 > 编程语言 > C#

C#倒计时--不要盲目选择Timer

2014-01-07 09:51 351 查看
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 = "暂停计时";

//this.timer1.Interval = 1;

//this.timer1.Start();

if (isstop == 0)//第一次执行或者倒计时事件设置发生变化,则重新倒计时

{

Timecount = Convert.ToInt32(txtTotalmm.Text) * 60000;//毫秒

Thread counter = new Thread(Counter);

counter.Start();

Control.CheckForIllegalCrossThreadCalls = false;//放弃捕获对错误线程的调用,否则在线程中无法调用控件名

this.txtTotalmm.ReadOnly = true;

this.button2.Visible = false;

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();

//label1.Text = hour.ToString() + "时 " + minute.ToString() + "分 " + second.ToString() + "秒" + millsecond + "毫秒";

if (Timecount == 0)

{

txthour.ForeColor = Color.Red;

txtmm.ForeColor = Color.Red;

txtss.ForeColor = Color.Red;

txtmss.ForeColor = Color.Red;

this.txtTotalmm.ReadOnly = false;

this.button2.Visible = true;

this.button1.Text = "开始计时";

isstop = 0;

try

{

Thread currthread = Thread.CurrentThread;

currthread.Abort();// 终止当前进程,会触发ThreadAbortException异常,从而终止进程,所以下面需要捕获该异常才能终止进程

}

catch (ThreadAbortException) { }

}

if (isstop != 2)

Timecount -= 1;

Thread.Sleep(1);

}

}

catch { }//处理异常关闭情况下的异常问题

}

private void button2_Click(object sender, EventArgs e)

{

this.txtTotalmm.Text = (Convert.ToInt32(this.txtTotalmm.Text) + 1).ToString();

}

//Timer控件的Interval频率值小于17时便会产生误差,所有得到的倒计时秒数比普通的慢很多,当倒计时精确到毫秒时,则不适用用Timer控件。

//private void timer1_Tick(object sender, EventArgs e)

//{

// if (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();

// //label1.Text = hour.ToString() + "时 " + minute.ToString() + "分 " + second.ToString() + "秒" + millsecond + "毫秒";

// if (Timecount == 0)

// {

// txthour.ForeColor = Color.Red;

// txtmm.ForeColor = Color.Red;

// txtss.ForeColor = Color.Red;

// txtmss.ForeColor = Color.Red;

// }

// Timecount -= 10;

// }

//}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: