Search This Blog

Friday, January 13, 2012

Silverlight 5 - Double Click and N-Click Support Edit

Silverlight 5 has introduced the concept of a click count. This works for both the left and right mouse buttons. This can be accomplished by the ClickCount property of the MouseButtonEventArgs class. This property tells you how many times the user has rapidly clicked the mouse button. 

XAML

<Grid x:Name="LayoutRoot" Background="White">
<Rectangle x:Name="ClickRectangle" Height="85" Width="93"
   HorizontalAlignment="Left" VerticalAlignment="Top" Margin="30,40,0,0"
   Stroke="Black" StrokeThickness="1" Fill="#FFE82A2A"
   MouseLeftButtonDown="RectMouseLeftButtonDown" />
</Grid>


C# Source Code

private TimeSpan _clickDelay = TimeSpan.FromMilliseconds(300);
private int _clickCount = 0;
private DispatcherTimer _timer = new DispatcherTimer();

void RectMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// This code would never allow for a triple click

//if (e.ClickCount == 2)

// MessageBox.Show("Double click!");

//else if (e.ClickCount == 3)

// MessageBox.Show("Triple click!");

_clickCount = e.ClickCount;

    if (e.ClickCount >= 2 && !_timer.IsEnabled)
   {
        // wait to see if we get a triple click
       _timer.Interval = _clickDelay;
       _timer.Tick += TimerTick;
       _timer.Start();
     }
else if (e.ClickCount < 2)
    {
      _timer.Stop();
    }
}
private void TimerTick(object sender, EventArgs e)
{
     _timer.Stop();
    _timer.Tick -= TimerTick;

      if (_clickCount == 2)
      OnRectDoubleClick();
      else if (_clickCount == 3)
      OnRectTripleClick();
}

private void OnRectDoubleClick()
{
    MessageBox.Show("Double Click!");
}

private void OnRectTripleClick()
{
    MessageBox.Show("Triple Click!");
}

No comments:

Post a Comment