WPF DispatcherTimer and Mouse Button Click Time

Consider the following code: I have a text block that is an on / off button in WPF. This is just text inside an ellipse that says ON / OFF. When the user presses the button and holds the left mouse button for ONE second, he will execute the code β€œturn on the device” if the device is not already turned on. If the user holds the ON / OFF button for three seconds or more (holds the left mouse button HELD down), the device will turn off.

A few problems that I miss the boat with. 1. A tick event does not fire when the mouse button is held, even though the timer is running. 2. The do / while loop never exits despite raising the button

Thanks!

    public int TimerCount = 0;

    private void ButtonPressTimer(object sender, EventArgs e)
    {
        TimerCount = TimerCount + 1;
    }

    private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        var buttonPressTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 1), DispatcherPriority.Normal, ButtonPressTimer, this.Dispatcher);

        do
        {
            if (!buttonPressTimer.IsEnabled)
                buttonPressTimer.Start();
        }
        while (e.ButtonState == MouseButtonState.Pressed);

        buttonPressTimer.Stop();
        if (TimerCount >= 3)
        {
            //do something here
        }
        else
        { 
            //do something different here
        }
    }
+3
3

, . , , , , .

private DateTime mousePressed;

private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    mousePressed = DateTime.Now;
}

private void txtBlockOnOff_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    // button released

    TimeSpan difference = DateTime.Now - mousePressed;

    if (difference.TotalSeconds >= 3)
    {
        // long press
    }
    else
    {
        // short press
    }
}
+5

, RepeatButton, , , , .

+3

- , Clicked.

: - - MousePressed? ( , , !) , WPF .

+1

Source: https://habr.com/ru/post/1709733/


All Articles