#732 – Basic Events for Raw Touch Input
January 11, 2013 1 Comment
WPF includes a set of events for handling raw touch input. These events are defined for all UIElement, ContentElement, and UIElement3D objects.
The most basic events are:
- TouchDown – User touches the screen
- TouchMove – User moves finger across the screen
- TouchUp – User lifts finger off the screen
Below is a simple example that allows drawing using touch. We’ve defined event handlers and attached them to a main Canvas element. A red circle is drawn at the TouchDown point and a blue circle at the TouchUp point. A continuous line is drawn as the user moves their finger across the screen.
private const double CircleWidth = 10; private Point LastPosition; private void Canvas_TouchDown(object sender, TouchEventArgs e) { try { TouchPoint tp = e.GetTouchPoint(null); AddEllipseAt(canvMain, tp.Position, Brushes.Red); LastPosition = tp.Position; } catch (Exception xx) { MessageBox.Show(xx.ToString()); } } private void Canvas_TouchMove(object sender, TouchEventArgs e) { TouchPoint tp = e.GetTouchPoint(null); AddLineFromTo(canvMain, LastPosition, tp.Position, Brushes.Black); LastPosition = tp.Position; } private void Canvas_TouchUp(object sender, TouchEventArgs e) { TouchPoint tp = e.GetTouchPoint(null); AddEllipseAt(canvMain, tp.Position, Brushes.Blue); } private void AddEllipseAt(Canvas canv, Point pt, Brush brush) { Ellipse el = new Ellipse(); el.Stroke = brush; el.Fill = brush; el.Width = CircleWidth; el.Height = CircleWidth; Canvas.SetLeft(el, pt.X - (CircleWidth / 2)); Canvas.SetTop(el, pt.Y - (CircleWidth / 2)); canv.Children.Add(el); } private void AddLineFromTo(Canvas canv, Point from, Point to, Brush brush) { Line l = new Line(); l.Stroke = brush; l.X1 = from.X; l.Y1 = from.Y; l.X2 = to.X; l.Y2 = to.Y; l.StrokeThickness = 2; canv.Children.Add(l); }
So when I touch and drag on a touch-enabled device, I get something that looks like this: