如何更改标签文本属性以显示2个事件之间的经过时间? [英] How Do I Change A Labels Text Property To Show The Elapsed Time Between 2 Events?

查看:89
本文介绍了如何更改标签文本属性以显示2个事件之间的经过时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在单击按钮时启动计时器,在单击其他按钮时结束计时器,并显示2个事件之间传递的时间量。我的代码在下面,计时器在私有类中声明。它从1个事件开始,在另一个事件中结束,并转换为int32。然后将其添加到int中,以获得经过时间的整数。然后将整数转换为字符串并放在标签中。不幸的是它只做间隔(1秒)。

I need to start a timer when a button is clicked, end it when a different button is clicked, and show the amount of time passed between the 2 events. My code is below and the timer is declared in a private class. It starts in 1 event, ends in another, and is converted to int32. This is then added to an int to give me an integer of the elapsed time. The integer is then converted to a string and placed in the label. Unfortunately it only does the interval (1 second).

private System.Timers.Timer Timer = new System.Timers.Timer(1000);
private void btnNewProblem_Click(object sender, EventArgs e)
{
     Timer.Start();
}
private void btnCheckAnswer_Click(object sender, EventArgs e)
{
    Timer.Stop();
    time += Convert.ToInt32(Timer.Interval) / 1000;
    lblTimer.Text = time.ToString() + " Second(s)";
 }



有几点需要注意:

1.我知道timer.interval是错误的。我在几个论坛上看到它后尝试了这个。

2.这是一个课程。教师希望它只在几秒钟内显示,并以间隔符号表示。

3.教练还希望它是计时器,而不是秒表。

提前致谢!


A few things to note:
1. I know timer.interval is wrong. I tried this after seeing it on several forums.
2. This is for a class. The instructor wants it to show in only seconds, and be in interval notation.
3. The instructor also wants it to be a timer and not a stop watch.
Thanks in advance!

推荐答案

使用 StopWatch [ ^ ] class。

Use the StopWatch[^] class.
Stopwatch stopwatch = new Stopwatch();

public Form1()
{
    InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
    stopwatch.Start();

}
private void button2_Click(object sender, EventArgs e)
{

    stopwatch.Stop();
    var milliSeocnds = stopwatch.ElapsedMilliseconds;
    MessageBox.Show(millSeconds + "milliseconds passed between the two clicks.");
}


这篇关于如何更改标签文本属性以显示2个事件之间的经过时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆