by Jim McCurdy
7. August 2009 22:32
Here is a simple static class, MouseButtonHelper, that offers a single method, IsDoubleClick, to determine if a standard MouseLeftButtonDown or MouseLeftButtonUp event is a double click. In the past I have used timers, and Triggers and Behaviors to accomplish the same thing, but this approach is less code, less XAML, and uses a lot less resources.
Usage is as follows:
- In XAML or in code behind, handle the standard MouseLeftButtonDown or MouseLeftButtonUp event for the object you wish to perform double click handling.
- Implement the handler function for the above event as follows:
public void OnMouseButtonDown(object sender, MouseButtonEventArgs e)
{
bool doubleClick = MouseButtonHelper.EventIsDoubleClick(sender, e);
if (doubleClick)
MessageBox.Show("Double click detected!", "Alert", MessageBoxButton.OK);
}
The code below has been tested and used with Silverlight 3 and Silverlight 4.
using System;
using System.Windows;
using System.Windows.Input;
namespace ClassLibrary
{
internal static class MouseButtonHelper
{
private const long k_DoubleClickSpeed = 500;
private const double k_MaxMoveDistance = 20;
private static long m_LastClickTicks = 0;
private static Point m_LastPosition;
private static object m_LastSender;
internal static bool IsDoubleClick(object sender, MouseButtonEventArgs e)
{
bool senderMatch = sender.Equals(m_LastSender);
m_LastSender = sender;
long clickTicks = DateTime.Now.Ticks;
Point position = e.GetPosition(null);
if (senderMatch)
{
long elapsedTicks = clickTicks - m_LastClickTicks;
long elapsedTime = elapsedTicks / TimeSpan.TicksPerMillisecond;
double distance = position.Distance(m_LastPosition);
if (elapsedTime <= k_DoubleClickSpeed && distance <= k_MaxMoveDistance)
{
// Double click!
m_LastClickTicks = 0;
return true;
}
}
// Not a double click
m_LastClickTicks = clickTicks;
m_LastPosition = position;
return false;
}
private static double Distance(this Point pointA, Point pointB)
{
double x = pointA.X - pointB.X;
double y = pointA.Y - pointB.Y;
return Math.Sqrt(x * x + y * y);
}
}
}