开发者

trying to add a "fast forward" like function to a button in c#

so i h开发者_JS百科ave a button, i'm trying to add a function that uses System.Diagnostics.Stopwatch to a button similar to a fast forward or rewind. when i hold down the button for a second i want it to do something stupid, like so:

private void button_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        var stopWatch = Stopwatch.StartNew();
        if (stopWatch.ElapsedTicks < 1000)
        {
            lbl1.Content = "Quickpress";
        }
        else if (stopWatch.ElapsedTicks >1000)
        {
            HAVE SOME ACTION HAPPEN HERE EVERY .5 SECONDS (how do i do it)
        }
    }

now, this is much simpler than what i want to do, but if the user presses the button for a long time, i want an action to happen every .5 seconds, how do i do it?

the mousedown event fires, it just always selects the short press, even if i hold the button down.


The RepeatButton is probably what you are looking for, it would encapsulate the periodic behavior but i don't know if there is a way to tell a short click from a holding click.

Edit: It seems to me you still need a field (well, you could use the Tag) to account for the state, e.g.

<RepeatButton
        Click="RepeatButton_Click"
        PreviewMouseLeftButtonUp="RepeatButton_MouseLeftButtonUp"
        Interval="500" Delay="1000" Content="Buton" />
int _clickCount = 0;
private void RepeatButton_Click(object sender, RoutedEventArgs e)
{
    if (_clickCount > 0)
    {
        // Repeated hold action
    }
    _clickCount++;
}

private void RepeatButton_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    if (_clickCount == 1)
    {
        // Short click action
    }
    _clickCount = 0;
}

(Note that the above code is far from clean, there are click logic issues for example as the reset should occur on mouse up but the short click action should only be performed if the mouse is still over the button, as the code is now the action will always happen (if the if condition is met of course))


You need to reuse the existing Stopwatch instance by storing it in a field in your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜