TouchDevice Class

Definition

Representa uma única entrada de toque produzida por um dedo na tela de toque.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
Inheritance
Implements

Examples

O exemplo a seguir permite que você crie padrões simples em um Canvas arrastando dois dedos em uma tela touch.The following example enables you to create simple patterns on a Canvas by dragging two fingers on a touchscreen. Cada toque é representado por um TouchDevice na TouchEventArgs.Each touch is represented by a TouchDevice in the TouchEventArgs. O padrão é criado com o desenho de uma linha entre os pontos de toque fornecidos pelos toques.The pattern is created by drawing a line between the touch points that are provided by the touches. Este exemplo requer uma tela compatível com o Windows Touch.This example requires a Windows Touch-compatible screen.

A marcação a seguir cria a interface do usuário, que consiste em um Canvas que é centralizado em uma grade e anexa os manipuladores de eventos para os 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>

O código a seguir manipula os eventos de toque.The following code handles the touch events. Quando um toque é pressionado na Canvas, o TouchDevice é capturado para o Canvas.When a touch is pressed on the Canvas, the TouchDevice is captured to the Canvas. Quando o toque é levantado, o TouchDevice é liberado.When the touch is lifted, the TouchDevice is released. Quando um toque se move na Canvas, a Id é verificada.When a touch moves on the Canvas, the Id is checked. Se a movimentação vier do primeiro toque, sua localização será registrada.If the move came from the first touch, its location is recorded. Se a movimentação vier do segundo toque, uma linha será desenhada da posição do primeiro toque para a posição do 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

Remarks

Normalmente, você acessa um TouchDevice usando a propriedade TouchEventArgs.TouchDevice.You typically access a TouchDevice by using the TouchEventArgs.TouchDevice property. Uma TouchDevice representa um único toque em uma tela.A TouchDevice represents a single touch on a screen. Se vários toques estiverem presentes, use a propriedade Id para diferenciá-los.If multiple touches are present, use the Id property to distinguish between them.

Note

Essa classe contém uma demanda de herança no nível de classe que se aplica a todos os membros.This class contains an inheritance demand at the class level that applies to all members. Um SecurityException é gerado quando a classe derivada não tem permissão de confiança total.A SecurityException is thrown when the derived class does not have full-trust permission. Para obter mais informações sobre as demandas de segurança, consulte demandas de link e demandas de herança.For more information about security demands, see Link Demands and Inheritance Demands.

Constructors

TouchDevice(Int32)

Chamado de construtores em classes derivadas para inicializar a classe TouchDevice.Called from constructors in derived classes to initialize the TouchDevice class.

Properties

ActiveSource

Obtém o PresentationSource que está relatando a entrada para este dispositivo.Gets the PresentationSource that is reporting input for this device.

Captured

Obtém o elemento que capturou o TouchDevice.Gets the element that captured the TouchDevice.

CaptureMode

Obtém a política de captura do TouchDevice.Gets the capture policy of the TouchDevice.

DirectlyOver

Obtém o elemento sobre o qual o ponto de contato de toque é direcionado.Gets the element that the touch contact point is directly over.

Dispatcher

Obtém o Dispatcher ao qual este DispatcherObject está associado.Gets the Dispatcher this DispatcherObject is associated with.

(Inherited from DispatcherObject)
Id

Obtém o identificador exclusivo do TouchDevice conforme fornecido pelo sistema operacional.Gets the unique identifier of the TouchDevice, as provided by the operating system.

IsActive

Obtém um valor que indica se o dispositivo está ativo.Gets a value that indicates whether the device is active.

Target

Obtém o elemento que recebe entrada do TouchDevice.Gets the element that receives input from the TouchDevice.

Methods

Activate()

Adiciona o TouchDevice ao sistema de mensagens de entrada.Adds the TouchDevice to the input messaging system.

Capture(IInputElement)

Captura um toque para o elemento especificado usando o modo de captura Element.Captures a touch to the specified element by using the Element capture mode.

Capture(IInputElement, CaptureMode)

Captura um toque para o elemento especificado usando o CaptureMode especificado.Captures a touch to the specified element by using the specified CaptureMode.

CheckAccess()

Determina se o thread de chamada tem acesso a este DispatcherObject.Determines whether the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)
Deactivate()

Remove o TouchDevice do sistema de mensagens de entrada.Removes the TouchDevice from the input messaging system.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetIntermediateTouchPoints(IInputElement)

Quando substituído em uma classe derivada, retorna todos os pontos de toque coletados entre os eventos de toque mais recentes e anteriores.When overridden in a derived class, returns all touch points that are collected between the most recent and previous touch events.

GetTouchPoint(IInputElement)

Retorna a posição atual do dispositivo de toque em relação ao elemento especificado.Returns the current position of the touch device relative to the specified element.

GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnCapture(IInputElement, CaptureMode)

Chamado quando um toque é capturado para um elemento.Called when a touch is captured to an element.

OnManipulationEnded(Boolean)

Chamado quando uma manipulação terminou.Called when a manipulation has ended.

OnManipulationStarted()

Chamado quando uma manipulação é iniciada.Called when a manipulation is started.

ReportDown()

Relata que um toque é pressionado em um elemento.Reports that a touch is pressed on an element.

ReportMove()

Relata um toque está se movendo em um elemento.Reports that a touch is moving across an element.

ReportUp()

Relata que um toque foi removido de um elemento.Reports that a touch was lifted from an element.

SetActiveSource(PresentationSource)

Define o PresentationSource que está relatando a entrada para este dispositivo.Sets the PresentationSource that is reporting input for this device.

Synchronize()

Força o TouchDevice a sincronizar a interface do usuário com os pontos de contato subjacentes.Forces the TouchDevice to synchronize the user interface with underlying touch points.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)
VerifyAccess()

Impõe que o thread de chamada tenha acesso a este DispatcherObject.Enforces that the calling thread has access to this DispatcherObject.

(Inherited from DispatcherObject)

Events

Activated

Ocorre quando o TouchDevice é adicionado ao sistema de mensagens de entrada.Occurs when the TouchDevice is added to the input messaging system.

Deactivated

Ocorre quando o TouchDevice é removido do sistema de mensagens de entrada.Occurs when the TouchDevice is removed from the input messaging system.

Updated

Ocorre quando uma mensagem de toque é enviada.Occurs when a touch message is sent.

Explicit Interface Implementations

IManipulator.GetPosition(IInputElement)

Retorna a posição do objeto IManipulator.Returns the position of the IManipulator object.

IManipulator.Id

Obtém o identificador exclusivo do TouchDevice conforme fornecido pelo sistema operacional.Gets the unique identifier of the TouchDevice as provided by the operating system.

IManipulator.ManipulationEnded(Boolean)

Ocorre quando uma manipulação terminou.Occurs when a manipulation has ended.

Applies to