user3209792
user3209792

Reputation: 35

Perform action only when button is held

How can I make a Button which executes the code under it only when the Button is pressed and held (let's say for one second) and stops when it is released?

Upvotes: 1

Views: 158

Answers (3)

MatDev8
MatDev8

Reputation: 986

You could use a Timer like this:

private void button1_MouseLeftDown(object sender, MouseEventArgs e)
{
   timer1.Enabled = true;
   timer1.Start();
}

private void button1_MouseLeftDown(object sender, MouseEventArgs e)
{
   timer1.Stop();
}

private void timer1_Tick(object sender, EventArgs e)
{
   // Do your job
}

But the best way is the Hold event.

Upvotes: 0

Sopuli
Sopuli

Reputation: 421

Button has a boolean IsPressed property which you can check; it is true when it's pressed down, false otherwise.

Also you can use several events. One way is to use TouchDown event, which triggers when you click on element via touch. And TouchUp triggers when the finger is lifted from the button.

You can read more here.

Upvotes: 0

lhan
lhan

Reputation: 4635

You shouldn't need to use any timers. The Button class contains an event for Hold.

You can use it like this:

<Button Hold="eventHandler"/>

Touch Input guide here.

Upvotes: 1

Related Questions