TouchDevice TouchDevice TouchDevice TouchDevice Class

Definición

Representa una única entrada táctil generada por un dedo en una pantalla táctil.Represents a single touch input produced by a finger on a touchscreen.

public ref class TouchDevice abstract : System::Windows::Input::InputDevice, System::Windows::Input::IManipulator
public abstract class TouchDevice : System.Windows.Input.InputDevice, System.Windows.Input.IManipulator
type TouchDevice = class
    inherit InputDevice
    interface IManipulator
Public MustInherit Class TouchDevice
Inherits InputDevice
Implements IManipulator
Herencia
Implementaciones

Ejemplos

El ejemplo siguiente le permite crear patrones simples en una Canvas arrastrando dos dedos en una pantalla táctil.The following example enables you to create simple patterns on a Canvas by dragging two fingers on a touchscreen. Cada entrada táctil se representa mediante TouchDevice un TouchEventArgsen.Each touch is represented by a TouchDevice in the TouchEventArgs. El patrón se crea dibujando una línea entre los puntos táctiles que proporcionan los toques.The pattern is created by drawing a line between the touch points that are provided by the touches. Este ejemplo requiere una pantalla compatible con Touch de Windows.This example requires a Windows Touch-compatible screen.

El siguiente marcado crea la interfaz de usuario, que consta de Canvas un que está centrado en una cuadrícula, y asocia los controladores de eventos para los eventos de toque.The following markup creates the user interface, which consists of a Canvas that is centered in a grid, and attaches the event handlers for the touch events.

<Window x:Class="WpfTouchEventsSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="525" Width="525">
    <Grid>
        <Canvas x:Name="canvas1"
                Width="500" Height="500"
                Background="Black"
                TouchDown="canvas_TouchDown"
                TouchMove="canvas_TouchMove"
                TouchUp="canvas_TouchUp" />
    </Grid>
</Window>

El código siguiente controla los eventos Touch.The following code handles the touch events. Cuando se presiona un toque en el Canvas TouchDevice , se captura en el Canvas.When a touch is pressed on the Canvas, the TouchDevice is captured to the Canvas. Cuando se eleva el toque, TouchDevice se libera.When the touch is lifted, the TouchDevice is released. Cuando una entrada táctil se mueve Canvasen el Id , se comprueba.When a touch moves on the Canvas, the Id is checked. Si el traslado procedía del primer toque, se registra su ubicación.If the move came from the first touch, its location is recorded. Si el traslado procedía del segundo toque, se dibuja una línea desde la posición del primer toque hasta la posición del segundo toque.If the move came from the second touch, a line is drawn from the position of the first touch to the position of the second touch.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;

namespace WpfTouchEventsSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        // Variables to track the first two touch points 
        // and the ID of the first touch point.
        private Point pt1, pt2 = new Point();
        private int firstTouchId = -1;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void canvas_TouchDown(object sender, TouchEventArgs e)
        {
            Canvas _canvas = (Canvas)sender as Canvas;
            if (_canvas != null)
            {
                _canvas.Children.Clear();
                e.TouchDevice.Capture(_canvas);

                // Record the ID of the first touch point if it hasn't been recorded.
                if (firstTouchId == -1)
                    firstTouchId = e.TouchDevice.Id;
            }
        }

        private void canvas_TouchMove(object sender, TouchEventArgs e)
        {
            Canvas _canvas = (Canvas)sender as Canvas;
            if (_canvas != null)
            {
                TouchPoint tp = e.GetTouchPoint(_canvas);
                // This is the first touch point; just record its position.
                if (e.TouchDevice.Id == firstTouchId)
                {
                    pt1.X = tp.Position.X;
                    pt1.Y = tp.Position.Y;
                }
                // This is not the first touch point; draw a line from the first point to this one.
                else if (e.TouchDevice.Id != firstTouchId)
                {
                    pt2.X = tp.Position.X;
                    pt2.Y = tp.Position.Y;

                    Line _line = new Line();
                    _line.Stroke = new RadialGradientBrush(Colors.White, Colors.Black);
                    _line.X1 = pt1.X;
                    _line.X2 = pt2.X;
                    _line.Y1 = pt1.Y;
                    _line.Y2 = pt2.Y;

                    _line.StrokeThickness = 2;
                    _canvas.Children.Add(_line);
                }
            }
        }

        private void canvas_TouchUp(object sender, TouchEventArgs e)
        {
            Canvas _canvas = (Canvas)sender as Canvas;
            if (_canvas != null && e.TouchDevice.Captured == _canvas)
            {
                _canvas.ReleaseTouchCapture(e.TouchDevice);
            }
        }
    }
}
Class MainWindow
    ' Variables to track the first two touch points 
    ' and the ID of the first touch point.
    Private pt1, pt2 As Point
    Private firstTouchId As Integer = -1
    ' Touch Down
    Private Sub canvas_TouchDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.TouchEventArgs)
        Dim _canvas As Canvas = CType(sender, Canvas)
        If (_canvas IsNot Nothing) Then
            _canvas.Children.Clear()
            e.TouchDevice.Capture(_canvas)

            ' Record the ID of the first touch point if it hasn't been recorded.
            If firstTouchId = -1 Then
                firstTouchId = e.TouchDevice.Id
            End If
        End If
    End Sub
    ' Touch Move
    Private Sub canvas_TouchMove(ByVal sender As System.Object, ByVal e As System.Windows.Input.TouchEventArgs)
        Dim _canvas As Canvas = CType(sender, Canvas)
        If (_canvas IsNot Nothing) Then
            Dim tp = e.GetTouchPoint(_canvas)
            ' This is the first touch point; just record its position.
            If e.TouchDevice.Id = firstTouchId Then
                pt1.X = tp.Position.X
                pt1.Y = tp.Position.Y

                ' This is not the first touch point; draw a line from the first point to this one.
            ElseIf e.TouchDevice.Id <> firstTouchId Then
                pt2.X = tp.Position.X
                pt2.Y = tp.Position.Y

                Dim _line As New Line()
                _line.Stroke = New RadialGradientBrush(Colors.White, Colors.Black)
                _line.X1 = pt1.X
                _line.X2 = pt2.X
                _line.Y1 = pt1.Y
                _line.Y2 = pt2.Y

                _line.StrokeThickness = 2
                _canvas.Children.Add(_line)
            End If
        End If
    End Sub
    ' Touch Up
    Private Sub canvas_TouchUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.TouchEventArgs)
        Dim _canvas As Canvas = CType(sender, Canvas)
        If (_canvas IsNot Nothing AndAlso e.TouchDevice.Captured Is _canvas) Then
            _canvas.ReleaseTouchCapture(e.TouchDevice)

        End If
    End Sub
End Class

Comentarios

Normalmente, se tiene TouchDevice acceso a mediante TouchEventArgs.TouchDevice la propiedad.You typically access a TouchDevice by using the TouchEventArgs.TouchDevice property. TouchDevice Representa una única entrada táctil en una pantalla.A TouchDevice represents a single touch on a screen. Si hay varios toques presentes, utilice la Id propiedad para distinguirlos.If multiple touches are present, use the Id property to distinguish between them.

Nota

Esta clase contiene una petición de herencia en el nivel de clase que se aplica a todos los miembros.This class contains an inheritance demand at the class level that applies to all members. Se SecurityException produce una excepción cuando la clase derivada no tiene permiso de plena confianza.A SecurityException is thrown when the derived class does not have full-trust permission. Para obtener más información sobre las demandas de seguridad, vea peticiones de vínculo y peticiones de herencia.For more information about security demands, see Link Demands and Inheritance Demands.

Constructores

TouchDevice(Int32) TouchDevice(Int32) TouchDevice(Int32) TouchDevice(Int32)

Se llama desde constructores de clases derivadas para inicializar la clase TouchDevice.Called from constructors in derived classes to initialize the TouchDevice class.

Propiedades

ActiveSource ActiveSource ActiveSource ActiveSource

Obtiene el objeto PresentationSource que proporciona la entrada para este dispositivo.Gets the PresentationSource that is reporting input for this device.

Captured Captured Captured Captured

Obtiene el elemento que capturó el objeto TouchDevice.Gets the element that captured the TouchDevice.

CaptureMode CaptureMode CaptureMode CaptureMode

Obtiene la directiva de captura de TouchDevice.Gets the capture policy of the TouchDevice.

DirectlyOver DirectlyOver DirectlyOver DirectlyOver

Obtiene el elemento sobre el que está justo encima el punto de contacto táctil.Gets the element that the touch contact point is directly over.

Dispatcher Dispatcher Dispatcher Dispatcher

Obtiene el objeto Dispatcher al que está asociado DispatcherObject.Gets the Dispatcher this DispatcherObject is associated with.

(Inherited from DispatcherObject)
Id Id Id Id

Obtiene el identificador único de TouchDevice, tal como lo proporciona el sistema operativo.Gets the unique identifier of the TouchDevice, as provided by the operating system.

IsActive IsActive IsActive IsActive

Obtiene un valor que indica si el dispositivo está activo.Gets a value that indicates whether the device is active.

Target Target Target Target

Obtiene el elemento que recibe la entrada desde TouchDevice.Gets the element that receives input from the TouchDevice.

Métodos

Activate() Activate() Activate() Activate()

Agrega TouchDevice al sistema de mensajería de entrada.Adds the TouchDevice to the input messaging system.

Capture(IInputElement) Capture(IInputElement) Capture(IInputElement) Capture(IInputElement)

Captura una entrada táctil en el elemento especificado usando el modo de captura de Element.Captures a touch to the specified element by using the Element capture mode.

Capture(IInputElement, CaptureMode) Capture(IInputElement, CaptureMode) Capture(IInputElement, CaptureMode) Capture(IInputElement, CaptureMode)

Captura una entrada táctil en el elemento especificado usando el CaptureMode indicado.Captures a touch to the specified element by using the specified CaptureMode.

CheckAccess() CheckAccess() CheckAccess() CheckAccess()

Determina si el subproceso de la llamada tiene acceso a DispatcherObject.Determines whether the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)
Deactivate() Deactivate() Deactivate() Deactivate()

Quita TouchDevice del sistema de mensajería de entrada.Removes the TouchDevice from the input messaging system.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetIntermediateTouchPoints(IInputElement) GetIntermediateTouchPoints(IInputElement) GetIntermediateTouchPoints(IInputElement) GetIntermediateTouchPoints(IInputElement)

Cuando se invalida en una clase derivada, devuelve los puntos táctiles recopilados entre el evento Touch más reciente y el evento Touch anterior.When overridden in a derived class, returns all touch points that are collected between the most recent and previous touch events.

GetTouchPoint(IInputElement) GetTouchPoint(IInputElement) GetTouchPoint(IInputElement) GetTouchPoint(IInputElement)

Devuelve la posición actual del dispositivo táctil con respecto al elemento especificado.Returns the current position of the touch device relative to the specified element.

GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnCapture(IInputElement, CaptureMode) OnCapture(IInputElement, CaptureMode) OnCapture(IInputElement, CaptureMode) OnCapture(IInputElement, CaptureMode)

Se le llama cuando se captura una entrada táctil en un elemento.Called when a touch is captured to an element.

OnManipulationEnded(Boolean) OnManipulationEnded(Boolean) OnManipulationEnded(Boolean) OnManipulationEnded(Boolean)

Se le llama cuando finaliza una manipulación.Called when a manipulation has ended.

OnManipulationStarted() OnManipulationStarted() OnManipulationStarted() OnManipulationStarted()

Se le llama cuando se inicia una manipulación.Called when a manipulation is started.

ReportDown() ReportDown() ReportDown() ReportDown()

Notifica que se ha presionado una entrada táctil en un elemento.Reports that a touch is pressed on an element.

ReportMove() ReportMove() ReportMove() ReportMove()

Notifica que una entrada táctil se está moviendo por un elemento.Reports that a touch is moving across an element.

ReportUp() ReportUp() ReportUp() ReportUp()

Notifica que una entrada táctil se levantó de un elemento.Reports that a touch was lifted from an element.

SetActiveSource(PresentationSource) SetActiveSource(PresentationSource) SetActiveSource(PresentationSource) SetActiveSource(PresentationSource)

Establece el objeto PresentationSource que notifica la entrada para este dispositivo.Sets the PresentationSource that is reporting input for this device.

Synchronize() Synchronize() Synchronize() Synchronize()

Fuerza a TouchDevice a sincronizar la interfaz de usuario con los puntos táctiles subyacentes.Forces the TouchDevice to synchronize the user interface with underlying touch points.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)
VerifyAccess() VerifyAccess() VerifyAccess() VerifyAccess()

Exige que el subproceso de la llamada tenga acceso a DispatcherObject.Enforces that the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)

Eventos

Activated Activated Activated Activated

Se produce cuando TouchDevice se agrega al sistema de mensajería de entrada.Occurs when the TouchDevice is added to the input messaging system.

Deactivated Deactivated Deactivated Deactivated

Se produce cuando TouchDevice se quita del sistema de mensajería de entrada.Occurs when the TouchDevice is removed from the input messaging system.

Updated Updated Updated Updated

Se produce cuando se envía un mensaje táctil.Occurs when a touch message is sent.

Implementaciones de interfaz explícitas

IManipulator.GetPosition(IInputElement) IManipulator.GetPosition(IInputElement) IManipulator.GetPosition(IInputElement) IManipulator.GetPosition(IInputElement)

Devuelve la posición del objeto IManipulator.Returns the position of the IManipulator object.

IManipulator.Id IManipulator.Id IManipulator.Id IManipulator.Id

Obtiene el identificador único de TouchDevice, tal como lo proporciona el sistema operativo.Gets the unique identifier of the TouchDevice as provided by the operating system.

IManipulator.ManipulationEnded(Boolean) IManipulator.ManipulationEnded(Boolean) IManipulator.ManipulationEnded(Boolean) IManipulator.ManipulationEnded(Boolean)

Se produce cuando finaliza una manipulación.Occurs when a manipulation has ended.

Seguridad

UIPermission
para derivar de esta clase.for deriving from this class. Acción de seguridad InheritanceDemand:.Security action: InheritanceDemand. Enumeración asociada:UnrestrictedAssociated enumeration: Unrestricted

Se aplica a