测量按钮1单击和按钮2单击之间的时间

时间:2018-11-23 21:37:11

标签: c# button

我需要测量按钮1单击和按钮2单击之间的时间。我知道我可以使用Datetime.Now,但是我分配的任何变量都只能在一个事件处理程序中使用。我在互联网上进行搜索,但我所能找到的只是使用秒表,但这在Visual Studio 2017中似乎不再起作用。

2 个答案:

答案 0 :(得分:2)

您可以使用秒表实例或DateTime计算。如果要使用秒表,还必须导入包含名称空间。

using System.Diagnostics;

无论哪种方式,您都必须将变量放在事件处理程序上方的作用域中,以便两个事件处理程序都可以访问它。这是一个使用这两种方法的Winforms示例,但是可以轻松地将其转换为其他方案。

using System;
using System.Diagnostics;
using System.Windows.Forms;

namespace WindowsFormsApp1 {
    public partial class Form1 : Form {
        private DateTime from;
        private Stopwatch watch = new Stopwatch();

        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            from = DateTime.Now;
            watch.Restart();
        }

        private void button2_Click(object sender, EventArgs e) {
            watch.Stop();
            MessageBox.Show(
                "Date subtraction: " + DateTime.Now.Subtract(from).ToString() + Environment.NewLine +
                "Stopwatch: " + watch.Elapsed.ToString());

        }
    }
}

答案 1 :(得分:0)

使用Stopwatch

Stopwatch _sw = new Stopwatch();

void Button1_Click(sender, e)
{
    if (_sw.IsRunning) 
        _sw.Stop();
    _sw.Reset();
    _sw.Start();
}


void Button2_Click(sender, e)
{
    if (_sw.IsRunning)   
        _sw.Stop();
    MessageBox.Show(_sw.Elapsed);
}

如果您使用的是Web窗体,则可以将秒表放入Session中。而且,在REST中,您可以使用运行时缓存。