Capture all Click or Touch events recursively in WPF

Doug picture Doug · Jun 4, 2012 · Viewed 9.5k times · Source

am pretty new to WPF, but am looking to capture whenever anyone touches inside a window or any child controls.

If I capture the click event for a Window, only the windows inner space capture the click. It's child controls do not.

How do i recursively capture any click/touch event ANYWHERE on the screen in a full size window?

many thanks in advance

Answer

RJ Lohan picture RJ Lohan · Jun 4, 2012

The routed event handling implementation in WPF is intended to give all controls in a nested hierarchy a chance to intercept and handle touch & mouse events. However, controls have the ability to prevent children from receiving the event notification.

There's a pretty good explanation of event routing here: http://nui.joshland.org/2010/04/why-wont-wpf-controls-work-with-touch.html

All controls receive a Preview event (for click or touch), and this cannot be prevented. After this, the event is 'promoted' to a regular Mouse/Touch event (touch is handled before click) However, if any control in the hierarchy for the 'click' (_MouseDown in WPF) event handling sets the Handled property on the event args to true, then the event will not be propagated any further.

Unless you are handling touch events or manipulations, or explicitly setting e.Handled = true in your code, then all controls in a nested stack should receive the _MouseDown event.

As noted in the comments below, some controls will set 'Handled = true' which would prevent their containers from receiving corresponding _TouchDown or _MouseDown events. However, they would all receive a PreviewTouch/PreviewMouseDown first.

Also note that handling touch events prevents handling of mouse events.