Procédure pas à pas : création de votre première application Touch

WPF permet aux applications de répondre à l’interaction tactile. Par exemple, vous pouvez interagir avec une application à l’aide d’un ou plusieurs doigts sur un appareil tactile, tel qu’un écran tactile, cette procédure pas à pas crée une application qui permet à l’utilisateur de déplacer, de redimensionner ou de faire pivoter un seul objet à l’aide de l’interaction tactile.

Prérequis

Vous devez disposer des éléments suivants pour exécuter cette procédure pas à pas :

  • Visual Studio.

  • Appareil qui accepte l’entrée tactile, telle qu’un écran tactile, qui prend en charge Windows Touch.

En outre, vous devez avoir une compréhension de base de la création d’une application dans WPF, en particulier comment s’abonner et gérer un événement. Pour plus d’informations, consultez Procédure pas à pas : ma première application de bureau WPF.

Création de l’application

Pour créer l'application

  1. Créez un projet d’application WPF en Visual Basic ou Visual C# nommé BasicManipulation. Pour plus d’informations, consultez Procédure pas à pas : ma première application de bureau WPF.

  2. Remplacez le contenu de MainWindow.xaml par le code XAML suivant.

    Ce balisage crée une application simple qui contient un rouge Rectangle sur un Canvas. La propriété du fichier Rectangle a la IsManipulationEnabled valeur true pour qu’elle reçoive des événements de manipulation. L’application s’abonne aux événements et ManipulationDeltaManipulationInertiaStarting aux ManipulationStartingévénements. Ces événements contiennent la logique permettant de déplacer le Rectangle moment où l’utilisateur le manipule.

    <Window x:Class="BasicManipulation.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Move, Size, and Rotate the Square"
            WindowState="Maximized"
            ManipulationStarting="Window_ManipulationStarting"
            ManipulationDelta="Window_ManipulationDelta"
            ManipulationInertiaStarting="Window_InertiaStarting">
      <Window.Resources>
    
        <!--The movement, rotation, and size of the Rectangle is 
            specified by its RenderTransform.-->
        <MatrixTransform x:Key="InitialMatrixTransform">
          <MatrixTransform.Matrix>
            <Matrix OffsetX="200" OffsetY="200"/>
          </MatrixTransform.Matrix>
        </MatrixTransform>
    
      </Window.Resources>
    
      <Canvas>
        <Rectangle Fill="Red" Name="manRect"
                     Width="200" Height="200" 
                     RenderTransform="{StaticResource InitialMatrixTransform}"
                     IsManipulationEnabled="true" />
      </Canvas>
    </Window>
    
    
  3. Si vous utilisez Visual Basic, dans la première ligne de MainWindow.xaml, remplacez x:Class="BasicManipulation.MainWindow" par x:Class="MainWindow".

  4. Dans la MainWindow classe, ajoutez le gestionnaire d’événements suivant ManipulationStarting .

    L’événement ManipulationStarting se produit lorsque WPF détecte que l’entrée tactile commence à manipuler un objet. Le code spécifie que la position de la manipulation doit être relative à celle-ci Window en définissant la ManipulationContainer propriété.

    void Window_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
    {
        e.ManipulationContainer = this;
        e.Handled = true;
    }
    
    Private Sub Window_ManipulationStarting(ByVal sender As Object, ByVal e As ManipulationStartingEventArgs)
        e.ManipulationContainer = Me
        e.Handled = True
    End Sub
    
  5. Dans la MainWindow classe, ajoutez le gestionnaire d’événements suivant ManipulationDelta .

    L’événement ManipulationDelta se produit lorsque l’entrée tactile change de position et peut se produire plusieurs fois pendant une manipulation. L’événement peut également se produire une fois qu’un doigt est déclenché. Par exemple, si l’utilisateur fait glisser un doigt sur un écran, l’événement ManipulationDelta se produit plusieurs fois au fur et à mesure que le doigt se déplace. Lorsque l’utilisateur déclenche un doigt à partir de l’écran, l’événement ManipulationDelta continue de se produire pour simuler l’inertie.

    Le code s’applique DeltaManipulation à l’élément Rectangle pour le RenderTransform déplacer à mesure que l’utilisateur déplace l’entrée tactile. Il case activée également si l’élément Rectangle est en dehors des limites du Window moment où l’événement se produit pendant l’inertie. Dans ce cas, l’application appelle la ManipulationDeltaEventArgs.Complete méthode pour mettre fin à la manipulation.

    void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
    {
    
        // Get the Rectangle and its RenderTransform matrix.
        Rectangle rectToMove = e.OriginalSource as Rectangle;
        Matrix rectsMatrix = ((MatrixTransform)rectToMove.RenderTransform).Matrix;
    
        // Rotate the Rectangle.
        rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
                             e.ManipulationOrigin.X,
                             e.ManipulationOrigin.Y);
    
        // Resize the Rectangle.  Keep it square
        // so use only the X value of Scale.
        rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
                            e.DeltaManipulation.Scale.X,
                            e.ManipulationOrigin.X,
                            e.ManipulationOrigin.Y);
    
        // Move the Rectangle.
        rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
                              e.DeltaManipulation.Translation.Y);
    
        // Apply the changes to the Rectangle.
        rectToMove.RenderTransform = new MatrixTransform(rectsMatrix);
    
        Rect containingRect =
            new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize);
    
        Rect shapeBounds =
            rectToMove.RenderTransform.TransformBounds(
                new Rect(rectToMove.RenderSize));
    
        // Check if the rectangle is completely in the window.
        // If it is not and intertia is occuring, stop the manipulation.
        if (e.IsInertial && !containingRect.Contains(shapeBounds))
        {
            e.Complete();
        }
    
        e.Handled = true;
    }
    
    Private Sub Window_ManipulationDelta(ByVal sender As Object, ByVal e As ManipulationDeltaEventArgs)
    
        ' Get the Rectangle and its RenderTransform matrix.
        Dim rectToMove As Rectangle = e.OriginalSource
        Dim rectTransform As MatrixTransform = rectToMove.RenderTransform
        Dim rectsMatrix As Matrix = rectTransform.Matrix
    
    
        ' Rotate the shape
        rectsMatrix.RotateAt(e.DeltaManipulation.Rotation,
                             e.ManipulationOrigin.X,
                             e.ManipulationOrigin.Y)
    
        ' Resize the Rectangle. Keep it square 
        ' so use only the X value of Scale.
        rectsMatrix.ScaleAt(e.DeltaManipulation.Scale.X,
                            e.DeltaManipulation.Scale.X,
                            e.ManipulationOrigin.X,
                            e.ManipulationOrigin.Y)
    
        'move the center
        rectsMatrix.Translate(e.DeltaManipulation.Translation.X,
                              e.DeltaManipulation.Translation.Y)
    
        ' Apply the changes to the Rectangle.
        rectTransform = New MatrixTransform(rectsMatrix)
        rectToMove.RenderTransform = rectTransform
    
        Dim container As FrameworkElement = e.ManipulationContainer
        Dim containingRect As New Rect(container.RenderSize)
    
        Dim shapeBounds As Rect = rectTransform.TransformBounds(
                                    New Rect(rectToMove.RenderSize))
    
        ' Check if the rectangle is completely in the window.
        ' If it is not and intertia is occuring, stop the manipulation.
        If e.IsInertial AndAlso Not containingRect.Contains(shapeBounds) Then
            e.Complete()
        End If
    
        e.Handled = True
    End Sub
    
  6. Dans la MainWindow classe, ajoutez le gestionnaire d’événements suivant ManipulationInertiaStarting .

    L’événement ManipulationInertiaStarting se produit lorsque l’utilisateur déclenche tous les doigts de l’écran. Le code définit la vitesse initiale et la décélération pour le mouvement, l’expansion et la rotation du rectangle.

    void Window_InertiaStarting(object sender, ManipulationInertiaStartingEventArgs e)
    {
    
        // Decrease the velocity of the Rectangle's movement by
        // 10 inches per second every second.
        // (10 inches * 96 pixels per inch / 1000ms^2)
        e.TranslationBehavior.DesiredDeceleration = 10.0 * 96.0 / (1000.0 * 1000.0);
    
        // Decrease the velocity of the Rectangle's resizing by
        // 0.1 inches per second every second.
        // (0.1 inches * 96 pixels per inch / (1000ms^2)
        e.ExpansionBehavior.DesiredDeceleration = 0.1 * 96 / (1000.0 * 1000.0);
    
        // Decrease the velocity of the Rectangle's rotation rate by
        // 2 rotations per second every second.
        // (2 * 360 degrees / (1000ms^2)
        e.RotationBehavior.DesiredDeceleration = 720 / (1000.0 * 1000.0);
    
        e.Handled = true;
    }
    
    Private Sub Window_InertiaStarting(ByVal sender As Object,
                                       ByVal e As ManipulationInertiaStartingEventArgs)
    
        ' Decrease the velocity of the Rectangle's movement by 
        ' 10 inches per second every second.
        ' (10 inches * 96 pixels per inch / 1000ms^2)
        e.TranslationBehavior.DesiredDeceleration = 10.0 * 96.0 / (1000.0 * 1000.0)
    
        ' Decrease the velocity of the Rectangle's resizing by 
        ' 0.1 inches per second every second.
        ' (0.1 inches * 96 pixels per inch / (1000ms^2)
        e.ExpansionBehavior.DesiredDeceleration = 0.1 * 96 / (1000.0 * 1000.0)
    
        ' Decrease the velocity of the Rectangle's rotation rate by 
        ' 2 rotations per second every second.
        ' (2 * 360 degrees / (1000ms^2)
        e.RotationBehavior.DesiredDeceleration = 720 / (1000.0 * 1000.0)
    
        e.Handled = True
    End Sub
    
  7. Générez et exécutez le projet.

    Vous devriez voir un carré rouge apparaître dans la fenêtre.

Test de l’application

Pour tester l’application, essayez les manipulations suivantes. Notez que vous pouvez effectuer plusieurs des opérations suivantes en même temps.

  • Pour déplacer le Rectangledoigt, placez un doigt sur l’écran Rectangle et déplacez le doigt sur l’écran.

  • Pour redimensionner le Rectangle, mettez deux doigts sur le Rectangle doigt et déplacez les doigts de plus près ou plus loin les uns des autres.

  • Pour faire pivoter le Rectangle, mettez deux doigts sur le Rectangle doigt et faites pivoter les doigts les uns autour des autres.

Pour provoquer l’inertie, déclenchez rapidement vos doigts à partir de l’écran lorsque vous effectuez les manipulations précédentes. Le Rectangle déplacement, le redimensionnement ou la rotation continuent pendant quelques secondes avant qu’il ne s’arrête.

Voir aussi