Detect the number of fingers in a windows store application

If you are using the touch API for windows store applications, then you might found yourself needing to detect the number of fingers that the user is touching the screen with.

Surprisingly there is no straightforward way to do this.

Below you find a helper class that gets you the number of touch points that are currently detected.

To use the class simply pass your the control that you want to monitor for touch points in the constructor.

Then query the number of touch points at any time:

var canvas = new Canvas();
var touchDetector = new NumberOfTouchPointsDetector(canvas);
// ...
int numberOfFingers = touchDetector.NumberOfTouchPoints ;

Here is the actual class:

using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Input;

public class NumberOfTouchPointsDetector
{
	#region Fields
	readonly HashSet<uint> _pointers = new HashSet<uint>();
	readonly UIElement _uiElement; 
	#endregion

	public int NumberOfTouchPoints { get { return _pointers.Count; } }

	public NumberOfTouchPointsDetector(UIElement uiElement)
	{
		_uiElement = uiElement;
		HookupEvents();
	} 
	
	public void UnHookEvents()
	{
		_uiElement.PointerPressed -= PointerPressed;
		_uiElement.PointerReleased -= PointerReleased;
		_uiElement.PointerExited -= PointerExited;
		_uiElement.PointerEntered -= PointerEntered;
		_uiElement.PointerCaptureLost -= PointerCaptureLost;
		_uiElement.PointerCanceled -= PointerCanceled;
	} 

	#region private
	private void PointerPressed(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Add(e.Pointer.PointerId);
	}
	
	private void PointerReleased(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Remove(GetPoint(e));
	}
	
	private void PointerExited(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Remove(GetPoint(e));
	}

	private void PointerEntered(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Add(GetPoint(e));
	}

	private void PointerCaptureLost(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Remove(GetPoint(e));
	}
	
	private void PointerCanceled(object sender, PointerRoutedEventArgs e)
	{
		_pointers.Clear();
	}

	uint GetPoint(PointerRoutedEventArgs e)
	{
		return e.GetCurrentPoint(_uiElement).PointerId;
	}

	private void HookupEvents()
	{
		_uiElement.PointerPressed += PointerPressed;
		_uiElement.PointerReleased += PointerReleased;
		_uiElement.PointerExited += PointerExited;
		_uiElement.PointerEntered += PointerEntered;
		_uiElement.PointerCaptureLost += PointerCaptureLost;
		_uiElement.PointerCanceled += PointerCanceled;
	} 
	#endregion
}