Manuj
Manuj

Reputation: 263

how to calculate button press time in c#?

There are various buttons in my form and for each button press an action is associated with it.I want to measure the time between button is pressed and released (in millisecs).How can I do it for each button.

Upvotes: 0

Views: 3951

Answers (3)

Tigran
Tigran

Reputation: 62276

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.

Upvotes: 2

Kami
Kami

Reputation: 19407

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

Upvotes: 1

Shadow Wizard
Shadow Wizard

Reputation: 66388

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

Upvotes: 7

Related Questions