Increment variable while holding a button

Asked

Viewed 453 times

0

I need to do an action inside a Button, when the person presses and holds with the left hand side of the mouse on the Button, increment a variable until release. Let go, to action.

Within the method of this Button, I want to increment the following variable:

int incrementar = 0;
incrementar++;

int valor = incrementar;
  • 1

    I don’t know c#, but by logic there must be the method that is called when you click and when you drop a button, in what is called when you click, you call another method that does a while(true), and in the drop you change the value to false

  • I don’t know what that method is, I tested a few here, but.. unsuccessfully.

2 answers

5


Put a Timer in your form, and set the range that the variable will increment while with the mouse pressed.

Done this, you use the Event MouseDown Button, to enable the timer, and the event MouseUp to disable:

int incremento = 0;

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

private void button2_MouseUp(object sender, MouseEventArgs e)
{
    timer1.Enabled = false;
    MessageBox.Show(incremento.ToString());
}

private void timer1_Tick(object sender, EventArgs e)
{
    incremento++;
}
  • 2

    That’s what I’m talking about haha, +1

-5

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="u" value="0" />

<input type="button" id="b" value="Aperte!" />

<script>
    $(function () {
        var timer;
    
        $('#b').on('mousedown mouseup', function (e) {
            switch (e.type) {
                case 'mouseup':
                    clearTimeout(timer);
                    break;
                case 'mousedown':
                    (function loop() {
                        timer = setTimeout(function () {
                            var u = +$('#u').val();
                            $('#u').val(++u);
                            loop();
                        }, 40);
                    })();
                    break;
            }
        });
    });
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.