-1

I know that there is a mouse click on a button, however I want my program to react to the button being held pressed with a given interval. I don't want the user to repeatedly be pressing on the button, instead he should just hold it.

Brookie_C
  • 427
  • 2
  • 10
  • 2
    Does this answer your question? [C# how to loop while mouse button is held down](https://stackoverflow.com/questions/4127270/c-sharp-how-to-loop-while-mouse-button-is-held-down) – Hayden Sep 07 '20 at 06:17

1 Answers1

0

Maybe you can try to achieve it via MouseDown, MouseUp and Timer.

First, create a new timer instance as followed.

    private System.Timers.Timer myTimer;
    int count = 0;

    private void myTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        count++;
        if(count == 3)
        {
            // this triggered when hold the button 3 seconds
            Console.WriteLine("execute command");
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.myTimer = new System.Timers.Timer(1000); // interval: 1s
        this.myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
        this.myTimer.AutoReset = true;
    }

Then, start the timer when mouse down and stop when mouse up.

private void button_MouseDown(object sender, MouseEventArgs e)
{
    // start the timer
    myTimer.Enabled = true;
    myTimer.Start();
}

private void button_MouseUp(object sender, MouseEventArgs e)
{
    // stop the timer
    myTimer.Stop();
    myTimer.Enabled = false;
    // reset counter
    count = 0;
}
大陸北方網友
  • 3,696
  • 3
  • 12
  • 37