Search code examples
c#eventsmouseevent

C# how to loop while mouse button is held down


Can you point me in the right direction? I'm trying to get a loop to trigger while the form button is depressed.

//pseudocode
While (button1 is pressed)
value1 += 1

And then of course stop looping when the button is released


Solution

  • To avoid using threads you can add a Timer component on your form/control and simply enable it on mouse down and disable it on mouse up. Then put the code you would normally put inside the loop in the Timer_Tick event. If you want to use System.Timers.Timer you can use the Timer.Elapsed event instead.

    Example (using System.Timers.Timer):

    using Timer = System.Timers.Timer;
    using System.Timers;
    using System.Windows.Forms;//WinForms example
    private static Timer loopTimer;
    private Button formButton;
    public YourForm()
    { 
        //loop timer
        loopTimer = new Timer();
        loopTimer.Interval = 500;/interval in milliseconds
        loopTimer.Enabled = false;
        loopTimer.Elapsed += loopTimerEvent;
        loopTimer.AutoReset = true;
        //form button
        formButton.MouseDown += mouseDownEvent;
        formButton.MouseUp += mouseUpEvent;
    }
    private static void loopTimerEvent(Object source, ElapsedEventArgs e)
    {
        //this does whatever you want to happen while clicking on the button
    }
    private static void mouseDownEvent(object sender, MouseEventArgs e)
    {
        loopTimer.Enabled = true;
    }
    private static void mouseUpEvent(object sender, MouseEventArgs e)
    {
        loopTimer.Enabled = false;
    }