Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long pressed button

I want to repeat an action when a Button is pressed during a long time, like for example the forward button of an MP3 reader. Is there an existing c# event in WinForm ?

I can handle the MouseDown event to start a timer which will perform the action and stop it on MouseUp event, but I am looking for an easier way to solve this problem => ie : a solution without a Timer (or Thread / Task ...).

like image 961
Emmanuel Chaffraix Avatar asked Oct 09 '12 09:10

Emmanuel Chaffraix


2 Answers

UPDATED: Shortest way:

Using Anonymous Methods and Object Initializer:

public void Repeater(Button btn, int interval)
{
    var timer = new Timer {Interval = interval};
    timer.Tick += (sender, e) => DoProgress();
    btn.MouseDown += (sender, e) => timer.Start();
    btn.MouseUp += (sender, e) => timer.Stop();
    btn.Disposed += (sender, e) =>
                        {
                            timer.Stop();
                            timer.Dispose();
                        };
}
like image 123
Ria Avatar answered Oct 01 '22 07:10

Ria


shortest way (and without any task/thread/timer & stopwatch) :)

DateTime sw;
bool buttonUp = false;
const int holdButtonDuration = 2000;
private void btnTest_MouseDown(object sender, MouseEventArgs e)
{
    buttonUp = false;
    sw = DateTime.Now;
    while (e.Button == MouseButtons.Left && e.Clicks == 1 && (buttonUp == false && (DateTime.Now - sw).TotalMilliseconds < holdButtonDuration))
        Application.DoEvents();
    if ((DateTime.Now - sw).TotalMilliseconds < holdButtonDuration)
        Test_ShortClick();
    else
        Test_LongClick();
}
private void btnTest_MouseUp(object sender, MouseEventArgs e)
{
    buttonUp = true;
}
like image 30
Ersin Kecis Avatar answered Oct 01 '22 05:10

Ersin Kecis