PointerRoutedEventArgs Classe

Definição

Contém os argumentos retornados pela mensagem de evento do último ponteiro.

public ref class PointerRoutedEventArgs sealed : RoutedEventArgs
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 65536)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class PointerRoutedEventArgs final : RoutedEventArgs
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 65536)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public sealed class PointerRoutedEventArgs : RoutedEventArgs
Public NotInheritable Class PointerRoutedEventArgs
Inherits RoutedEventArgs
Herança
Object Platform::Object IInspectable RoutedEventArgs PointerRoutedEventArgs
Atributos

Requisitos do Windows

Família de dispositivos
Windows 10 (introduzida na 10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduzida na v1.0)

Exemplos

O exemplo de código a seguir mostra o cenário 2 do exemplo de entrada. Esse código mostra alguns padrões de uso para manipulação direta usando os eventos PointerPressed, PointerReleased, PointerEntered, PointerExited e PointerMoved .

<StackPanel x:Name="Scenario2Output" ManipulationMode="All">
  <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
    <Button x:Name="scenario2Reset" Content="Reset" 
      Margin="0,0,10,0" Click="Scenario2Reset"/>
  </StackPanel>
  <StackPanel Orientation="Horizontal" >
    <ToggleSwitch x:Name="tbPointerCapture" 
      Header="Pointer Capture" FontSize="20"/>
    <TextBlock x:Name="txtCaptureStatus" 
      Style="{StaticResource BasicTextStyle}"/>
  </StackPanel>
  <Border x:Name="bEnteredExited" Background="Red" 
    Height="300" Width="450" CornerRadius="20" 
    HorizontalAlignment="Left">
    <Grid>
      <TextBlock Style="{StaticResource BasicTextStyle}" Text="" 
        HorizontalAlignment="Center" VerticalAlignment="Center" 
        x:Name="bEnteredExitedTextBlock"/>
      <Ellipse VerticalAlignment="Bottom" Stroke="Silver" 
        StrokeDashArray="2,2" StrokeThickness="2" Margin="2" 
        x:Name="bEnteredExitedTimer" Width="20" Height="20" 
        RenderTransformOrigin="0.5,0.5">
        <Ellipse.RenderTransform >
          <RotateTransform Angle="0" />
        </Ellipse.RenderTransform>
      </Ellipse>
    </Grid>
  </Border>
</StackPanel>
int _pointerCount;

public Scenario2()
{
    this.InitializeComponent();
    bEnteredExited.PointerEntered += bEnteredExited_PointerEntered;
    bEnteredExited.PointerExited += bEnteredExited_PointerExited;
    bEnteredExited.PointerPressed += bEnteredExited_PointerPressed;
    bEnteredExited.PointerReleased += bEnteredExited_PointerReleased;
    bEnteredExited.PointerMoved += bEnteredExited_PointerMoved;

    // To code for multiple Pointers (that is, fingers), 
    // we track how many entered/exited.
    _pointerCount = 0;
}

private void bEnteredExited_PointerMoved(object sender, 
    PointerRoutedEventArgs e)
{
    Scenario2UpdateVisuals(sender as Border, "Moved");
}

private void bEnteredExited_PointerReleased(object sender, 
    PointerRoutedEventArgs e)
{
    ((Border)sender).ReleasePointerCapture(e.Pointer);
    txtCaptureStatus.Text = string.Empty;
}

//Can only get capture on PointerPressed (i.e. touch down, mouse click, pen press)
private void bEnteredExited_PointerPressed(object sender, 
    PointerRoutedEventArgs e)
{
    if (tbPointerCapture.IsOn)
    {
        bool _hasCapture = ((Border)sender).CapturePointer(e.Pointer);
        txtCaptureStatus.Text = "Got Capture: " + _hasCapture;
    }
}

private void bEnteredExited_PointerExited(object sender, 
    PointerRoutedEventArgs e)
{
    _pointerCount--;
    Scenario2UpdateVisuals(sender as Border, "Exited");
}

private void bEnteredExited_PointerEntered(object sender, 
    PointerRoutedEventArgs e)
{
    _pointerCount++;
    Scenario2UpdateVisuals(sender as Border, "Entered");
}

private void Scenario2UpdateVisuals(Border border, 
    String eventDescription)
{
    switch (eventDescription.ToLower())
    {
        case "exited":
            if (_pointerCount <= 0)
            {
                border.Background = new SolidColorBrush(Colors.Red);
                bEnteredExitedTextBlock.Text = eventDescription;
            }
            break;
        case "moved":
            RotateTransform rt = 
                (RotateTransform)bEnteredExitedTimer.RenderTransform;
            rt.Angle += 2;
            if (rt.Angle > 360) rt.Angle -= 360;
            break;
        default:
            border.Background = new SolidColorBrush(Colors.Green);
            bEnteredExitedTextBlock.Text = eventDescription;
            break;
    }
}

private void Scenario2Reset(object sender, RoutedEventArgs e)
{
    Scenario2Reset();
}

private void Scenario2Reset()
{
    bEnteredExited.Background = new SolidColorBrush(Colors.Green);
    bEnteredExitedTextBlock.Text = string.Empty;
}
Private _pointerCount As Integer

Public Sub New()
    Me.InitializeComponent()
    AddHandler bEnteredExited.PointerEntered, AddressOf bEnteredExited_PointerEntered
    AddHandler bEnteredExited.PointerExited, AddressOf bEnteredExited_PointerExited
    AddHandler bEnteredExited.PointerPressed, AddressOf bEnteredExited_PointerPressed
    AddHandler bEnteredExited.PointerReleased, AddressOf bEnteredExited_PointerReleased
    AddHandler bEnteredExited.PointerMoved, AddressOf bEnteredExited_PointerMoved

    'To code for multiple Pointers (i.e. Fingers) we track how many entered/exited.
    _pointerCount = 0
End Sub

''' <summary>
''' Invoked when this page is about to be displayed in a Frame.
''' </summary>
''' <param name="e">Event data that describes how this page was reached.  The Parameter
''' property is typically used to configure the page.</param>
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
End Sub

Private Sub bEnteredExited_PointerMoved(sender As Object, e As PointerRoutedEventArgs)
    Scenario2UpdateVisuals(TryCast(sender, Border), "Moved")
End Sub

Private Sub bEnteredExited_PointerReleased(sender As Object, e As PointerRoutedEventArgs)
    DirectCast(sender, Border).ReleasePointerCapture(e.Pointer)
    txtCaptureStatus.Text = String.Empty
End Sub

'Can only get capture on PointerPressed (i.e. touch down, mouse click, pen press)
Private Sub bEnteredExited_PointerPressed(sender As Object, e As PointerRoutedEventArgs)
    If tbPointerCapture.IsOn Then
        Dim _hasCapture As Boolean = DirectCast(sender, Border).CapturePointer(e.Pointer)
        txtCaptureStatus.Text = "Got Capture: " & _hasCapture
    End If
End Sub

Private Sub bEnteredExited_PointerExited(sender As Object, e As PointerRoutedEventArgs)
    _pointerCount -= 1
    Scenario2UpdateVisuals(TryCast(sender, Border), "Exited")
End Sub

Private Sub bEnteredExited_PointerEntered(sender As Object, e As PointerRoutedEventArgs)
    _pointerCount += 1
    Scenario2UpdateVisuals(TryCast(sender, Border), "Entered")

End Sub

Private Sub Scenario2UpdateVisuals(border As Border, eventDescription As String)
    Select Case eventDescription.ToLower()
        Case "exited"
            If _pointerCount <= 0 Then
                border.Background = New SolidColorBrush(Colors.Red)
                bEnteredExitedTextBlock.Text = eventDescription
            End If
            Exit Select
        Case "moved"

            Dim rt As RotateTransform = DirectCast(bEnteredExitedTimer.RenderTransform, RotateTransform)
            rt.Angle += 2
            If rt.Angle > 360 Then
                rt.Angle -= 360
            End If
            Exit Select
        Case Else
            border.Background = New SolidColorBrush(Colors.Green)
            bEnteredExitedTextBlock.Text = eventDescription
            Exit Select

    End Select
End Sub

Private Sub Scenario2ResetMethod(sender As Object, e As RoutedEventArgs)
    Reset()
End Sub

Private Sub Reset()
    bEnteredExited.Background = New SolidColorBrush(Colors.Green)
    bEnteredExitedTextBlock.Text = String.Empty
End Sub

Comentários

Na maioria dos casos, recomendamos que você obtenha informações de ponteiro por meio do argumento de evento dos manipuladores de eventos de ponteiro na estrutura de linguagem escolhida (aplicativo do Windows usando JavaScript, aplicativo UWP usando C++, C#ou Visual Basic ou aplicativo UWP usando DirectX com C++).

Se o argumento de evento não expor intrinsecamente os detalhes do ponteiro exigidos pelo aplicativo, você poderá obter acesso a dados de ponteiro estendidos por meio dos métodos GetCurrentPoint e GetIntermediatePoints de PointerRoutedEventArgs. Use esses métodos para especificar o contexto dos dados do ponteiro.

Os métodos PointerPoint estáticos, GetCurrentPoint e GetIntermediatePoints, sempre usam o contexto do aplicativo. A classe de dados de evento PointerRoutedEventArgs é usada para estes eventos:

Importante

A entrada do mouse é associada a um único ponteiro atribuído quando detectada pela primeira vez. Se o usuário clicar em um botão do mouse (esquerdo, roda ou direito), será criada uma associação secundária entre o ponteiro e esse botão por meio do evento PointerPressed. O evento PointerReleased é disparado somente quando esse mesmo botão do mouse é liberado (nenhum outro botão pode ser associado ao ponteiro até que o evento seja concluído). Devido a essa associação exclusiva, outros cliques em botões do mouse são roteados por meio do evento PointerMoved. Você pode testar o estado do botão do mouse ao manipular esse evento, conforme mostrado no exemplo a seguir.

private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    Windows.UI.Xaml.Input.Pointer ptr = e.Pointer;

    // Multiple, simultaneous mouse button inputs are processed here.
    // Mouse input is associated with a single pointer assigned when 
    // mouse input is first detected. 
    // Clicking additional mouse buttons (left, wheel, or right) during 
    // the interaction creates secondary associations between those buttons 
    // and the pointer through the pointer pressed event. 
    // The pointer released event is fired only when the last mouse button 
    // associated with the interaction (not necessarily the initial button) 
    // is released. 
    // Because of this exclusive association, other mouse button clicks are 
    // routed through the pointer move event.          
    if (ptr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
    {
        // To get mouse state, we need extended pointer details.
        // We get the pointer info through the getCurrentPoint method
        // of the event argument. 
        Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(Target);
        if (ptrPt.Properties.IsLeftButtonPressed)
        {
            eventLog.Text += "\nLeft button: " + ptrPt.PointerId;
        }
        if (ptrPt.Properties.IsMiddleButtonPressed)
        {
            eventLog.Text += "\nWheel button: " + ptrPt.PointerId;
        }
        if (ptrPt.Properties.IsRightButtonPressed)
        {
            eventLog.Text += "\nRight button: " + ptrPt.PointerId;
        }
    }

    // Prevent most handlers along the event route from handling the same event again.
    e.Handled = true;

    // Display pointer details.
    updateInfoPop(e);
}
private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
{
    Windows.UI.Xaml.Input.Pointer ptr = e.Pointer;

    // Multiple, simultaneous mouse button inputs are processed here.
    // Mouse input is associated with a single pointer assigned when 
    // mouse input is first detected. 
    // Clicking additional mouse buttons (left, wheel, or right) during 
    // the interaction creates secondary associations between those buttons 
    // and the pointer through the pointer pressed event. 
    // The pointer released event is fired only when the last mouse button 
    // associated with the interaction (not necessarily the initial button) 
    // is released. 
    // Because of this exclusive association, other mouse button clicks are 
    // routed through the pointer move event.          
    if (ptr.PointerDeviceType == Windows.Devices.Input.PointerDeviceType.Mouse)
    {
        // To get mouse state, we need extended pointer details.
        // We get the pointer info through the getCurrentPoint method
        // of the event argument. 
        Windows.UI.Input.PointerPoint ptrPt = e.GetCurrentPoint(Target);
        if (ptrPt.Properties.IsLeftButtonPressed)
        {
            eventLog.Text += "\nLeft button: " + ptrPt.PointerId;
        }
        if (ptrPt.Properties.IsMiddleButtonPressed)
        {
            eventLog.Text += "\nWheel button: " + ptrPt.PointerId;
        }
        if (ptrPt.Properties.IsRightButtonPressed)
        {
            eventLog.Text += "\nRight button: " + ptrPt.PointerId;
        }
    }

    // Prevent most handlers along the event route from handling the same event again.
    e.Handled = true;

    // Display pointer details.
    updateInfoPop(e);
}

Eventos específicos geralmente têm informações disponíveis nas várias classes de ponto de ponteiro e dispositivo de ponteiro que são relevantes principalmente apenas para esse evento. Por exemplo, ao manipular PointerWheelChanged, talvez você esteja interessado no MouseWheelDelta de PointerPointProperties.

O objeto recuperado pelos métodos GetCurrentPoint e GetIntermediatePoints fornece acesso a informações de ponteiro estendido por meio da propriedade Properties , que obtém um objeto PointerPointProperties .

No exemplo a seguir, obtemos propriedades de ponteiro estendido por meio dos objetos PointerPoint e PointerPointProperties . (Consulte Início Rápido: Ponteiros para o exemplo completo.)

String queryPointer(PointerPoint ptrPt)
{
    String details = "";

    switch (ptrPt.PointerDevice.PointerDeviceType)
    {
        case Windows.Devices.Input.PointerDeviceType.Mouse:
            details += "\nPointer type: mouse";
            break;
        case Windows.Devices.Input.PointerDeviceType.Pen:
            details += "\nPointer type: pen";
            if (ptrPt.IsInContact)
            {
                details += "\nPressure: " + ptrPt.Properties.Pressure;
                details += "\nrotation: " + ptrPt.Properties.Orientation;
                details += "\nTilt X: " + ptrPt.Properties.XTilt;
                details += "\nTilt Y: " + ptrPt.Properties.YTilt;
                details += "\nBarrel button pressed: " + ptrPt.Properties.IsBarrelButtonPressed;
            }
            break;
        case Windows.Devices.Input.PointerDeviceType.Touch:
            details += "\nPointer type: touch";
            details += "\nrotation: " + ptrPt.Properties.Orientation;
            details += "\nTilt X: " + ptrPt.Properties.XTilt;
            details += "\nTilt Y: " + ptrPt.Properties.YTilt;
            break;
        default:
            details += "\nPointer type: n/a";
            break;
    }

    GeneralTransform gt = Target.TransformToVisual(page);
    Point screenPoint;

    screenPoint = gt.TransformPoint(new Point(ptrPt.Position.X, ptrPt.Position.Y));
    details += "\nPointer Id: " + ptrPt.PointerId.ToString() +
        "\nPointer location (parent): " + ptrPt.Position.X + ", " + ptrPt.Position.Y +
        "\nPointer location (screen): " + screenPoint.X + ", " + screenPoint.Y;
    return details;
}

Normalmente, o objeto retornado por esse método é usado para alimentar dados de ponteiro para um GestureRecognizer. Outro cenário é obter o MouseWheelDelta para um evento PointerWheelChanged ; esse valor está em PointerPointProperties.

Histórico de versão

Versão do Windows Versão do SDK Valor adicionado
1.709 16299 IsGenerated

Propriedades

Handled

Obtém ou define um valor que marca o evento roteado como manipulado e impede que a maioria dos manipuladores ao longo da rota de evento manipule o mesmo evento novamente.

IsGenerated

Obtém um valor que indica se o evento de ponteiro ocorreu por interação direta com um objeto pelo usuário ou foi gerado pela plataforma com base em alterações na interface do usuário do aplicativo.

KeyModifiers

Obtém um valor que indica quais modificadores de chave estavam ativos no momento em que o evento de ponteiro foi iniciado.

OriginalSource

Obtém uma referência ao objeto que gerou o evento. Isso geralmente é uma parte de modelo de um controle em vez de um elemento que foi declarado na interface do usuário do aplicativo.

(Herdado de RoutedEventArgs)
Pointer

Obtém uma referência a um token de ponteiro.

Métodos

GetCurrentPoint(UIElement)

Recupera um objeto PointerPoint que fornece informações básicas sobre o ponteiro associado ao evento.

GetIntermediatePoints(UIElement)

Recupera uma coleção de objetos PointerPoint que representam o histórico de ponteiro do último evento de ponteiro até e incluindo o evento de ponteiro atual. Cada PointerPoint na coleção fornece informações básicas sobre o ponteiro associado ao evento. O último item da coleção é equivalente ao objeto PointerPoint retornado por GetCurrentPoint.

Aplica-se a

Confira também