简体   繁体   中英

how to calculate button press time in c#?

我的表单中有各种按钮,每按一次按钮都会有一个动作与之相关。我想测量按钮被按下和释放之间的时间(以毫秒为单位),如何为每个按钮做到这一点。

In the Form_Load event you can iterate all buttons and dynamically attach Stopwatch to each of them, then handle their MouseDown and MouseUp events:

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

And the functions:

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

Can measure the time span using StopWatch , or use a performance profiler , like
Equatec , which has a free option too.

StopWatch relative StartNew and Stop mthods can inject, in front and at the end of the event handler.

You need to capture the KeyDown and MouseDown for the down event and the KeyUp and MouseUp for the up event.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM