Increment variable while holding a button

0

I need to do an action inside a Button, when the person presses and holds with the left side of the Button in the Button, increment a variable until you release. He released, for action.

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

int incrementar = 0;
incrementar++;

int valor = incrementar;
    
asked by anonymous 21.06.2018 / 20:47

2 answers

5

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

Once you have done this, you use the% Button% Event, to enable the timer, and the MouseDown event 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++;
}
    
21.06.2018 / 21:08
-5

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="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>
    
21.06.2018 / 21:34