如何计算c#中的按键时间?

时间:2012-12-18 11:54:43

标签: c# winforms

我的表单中有各种按钮,按下每个按钮都会关闭一个动作。我想测量按下和释放按钮之间的时间(以毫秒为单位)。我如何为每个按钮执行此操作。

3 个答案:

答案 0 :(得分:7)

在Form_Load事件中,您可以迭代所有按钮并动态地将秒表附加到每个按钮,然后处理它们的MouseDown和MouseUp事件:

this.Controls.OfType<Button>().ToList().ForEach(button =>
{
    button.Tag = new Stopwatch();
    button.MouseDown += new MouseEventHandler(button_MouseDown);
    button.MouseUp += new MouseEventHandler(button_MouseUp);
});

功能:

void button_MouseUp(object sender, MouseEventArgs e)
{
    Stopwatch watch = ((sender as Button).Tag as Stopwatch);
    watch.Stop();
    MessageBox.Show("This button was clicked for " + watch.Elapsed.TotalMilliseconds + " milliseconds");
    watch.Reset();
}

void button_MouseDown(object sender, MouseEventArgs e)
{
    ((sender as Button).Tag as Stopwatch).Start();
}

答案 1 :(得分:2)

可以使用StopWatch衡量时间跨度,或使用性能分析器,例如
Equatec,也有免费选项。

StopWatch相对StartNewStop方法可以在事件处理程序的前端和末尾注入。

答案 2 :(得分:1)

您需要捕获向下事件的KeyDownMouseDown以及向上事件的KeyUpMouseUp

    public Form1()
    {
        InitializeComponent();
        button1.KeyDown += new KeyEventHandler(button1_down);
        button1.MouseDown+=new MouseEventHandler(button1_down);

        button1.KeyUp += new KeyEventHandler(button1_Up);
        button1.MouseUp += new MouseEventHandler(button1_Up);
    }

    void button1_down(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
    }

    private void button1_Up(object sender, EventArgs e)
    {
        Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
    }