1. 直接用winform 的 timers
拖控件进去
代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int sum = 0;
int qian;
int bai;
int shi;
int ge;
private void Form1_Load(object sender, EventArgs e)//初始化
{
textBox1.Text = "00.00";
timer1.Interval = 1000;
timer1.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Owner = this;
this.Hide();
f2.Show(); //窗体2返回在窗体2写代码 this.Hide(); this.Owner.Show();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)//winform的timer,不精确
{
sum++;
qian = sum / 1000;
bai = sum % 1000 / 100;
shi = sum % 100 / 10;
ge = sum % 10;
textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString();
}
2.使用System.Timers.Timer
先定义System.Timers.Timer t;
private void Form1_Load(object sender, EventArgs e)//初始化
{
textBox1.Text = "00.00";
t = new System.Timers.Timer(1000);
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
}
private void button2_Click(object sender, EventArgs e)
{
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
//如果不写下面这句会有一个异常。
//异常:线程间操作无效: 从不是创建控件"richtextbox"的线程访问它
//但这不是最好的方法。如果只有一个进程调用richtextbox而已。就可以用下面这句
//如果有多个线程调用richtextbox等控件。就要用委托。见thread第二种方法
Control.CheckForIllegalCrossThreadCalls = false;
}
private void theout(object sender, EventArgs e)
{
sum++;
qian = sum / 1000;
bai = sum % 1000 / 100;
shi = sum % 100 / 10;
ge = sum % 10;
textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString();
}
3.thread
Thread th;//定义线程
private void Form1_Load(object sender, EventArgs e)//初始化
{
textBox1.Text = "00.00";
th=new Thread(calculate);
th.IsBackground = true;
}
private void button2_Click(object sender, EventArgs e)
{
th.Start();
//Control.CheckForIllegalCrossThreadCalls = false; 同2,不写会报错
}
private void calculate()//线程的第一种方法
{
while(true)
{
sum++;
qian = sum / 1000;
bai = sum % 1000 / 100;
shi = sum % 100 / 10;
ge = sum % 10;
textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString();
Thread.Sleep(1000);
}
}
下面第二种方法:
private delegate void FlushClient();//定义委托
private void Form1_Load(object sender, EventArgs e)//初始化
{
textBox1.Text = "00.00";
th = new Thread(CrossThreadFlush);//线程第二种方法
th.IsBackground = true;
}
private void CrossThreadFlush()//第二种方法
{
while (true)
{
Thread.Sleep(1000);
ThreadFunction();
}
}
private void ThreadFunction()//第二种方法
{
if (this.textBox1.InvokeRequired)//等待异步
{
FlushClient fc = new FlushClient(ThreadFunction);
this.Invoke(fc);//通过代理调用刷新方法
}
else
{
sum++;
qian = sum / 1000;
bai = sum % 1000 / 100;
shi = sum % 100 / 10;
ge = sum % 10;
textBox1.Text = qian.ToString() + bai.ToString() + "." + shi.ToString() + ge.ToString();
}
}