Partager via


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

WPF active la sensibilité tactile des applications. Par exemple, vous pouvez interagir avec une application en utilisant un ou plusieurs doigts sur un périphérique avec sensibilité tactile, tel qu'un écran tactile. Cette procédure pas à pas crée une application qui permet à l'utilisateur de déplacer, redimensionner ou faire pivoter un objet unique à l'aide de fonctions tactiles.

Composants requis

Pour exécuter cette procédure pas à pas, vous devez disposer des composants suivants :

  • Microsoft Visual Studio 2010.

  • Windows 7,

  • périphérique qui accepte les entrées tactiles, tel qu'un écran tactile, qui prend en charge l'interface tactile Windows.

En outre, vous devez avoir une connaissance de base sur la création d'une application dans WPF, en particulier sur la façon de s'abonner à un événement et de le gérer. Pour plus d'informations, consultez Procédure pas à pas : mise en route de WPF.

Création de l'application

Pour créer l'application

  1. Créez un projet d'application WPF dans Visual Basic ou Visual C# nommé ManipulationDeBase. Pour plus d'informations, consultez Comment : créer un projet d'application WPF.

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

    Ce balisage crée une application simple qui contient un Rectangle rouge sur un Canvas. La propriété IsManipulationEnabled du Rectangle a la valeur true afin qu'il reçoive les événements de manipulation. L'application s'abonne aux événements ManipulationStarting, ManipulationDelta et ManipulationInertiaStarting. Ces événements contiennent la logique permettant de déplacer le Rectangle lorsque l'utilisateur le manipule.

    <Window x:Class="BasicManipulation.MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://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 classe MainWindow, ajoutez le gestionnaire d'événements ManipulationStarting.

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

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

    L'événement ManipulationDelta se produit lorsque l'entrée tactile modifie la position et peut avoir lieu plusieurs fois pendant une manipulation. L'événement peut également se produire après qu'un doigt soit enlevé. Par exemple, si l'utilisateur fait glisser un doigt sur l'écran, l'événement ManipulationDelta se produit plusieurs fois au fil du déplacement du doigt. Lorsque l'utilisateur enlève un doigt de l'écran, l'événement ManipulationDelta continue de se produire pour simuler l'inertie.

    Le code applique la DeltaManipulation au RenderTransform du Rectangle pour le déplacer tandis que l'utilisateur déplace l'entrée tactile. Il vérifie également si le Rectangle se situe à l'extérieur des limites de la Window lorsque l'événement se produit pendant l'inertie. Le cas échéant, l'application appelle la méthode ManipulationDeltaEventArgs.Complete pour terminer la manipulation.

    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
    
    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;
    }
    
  6. Dans la classe MainWindow, ajoutez le gestionnaire d'événements ManipulationInertiaStarting suivant.

    L'événement ManipulationInertiaStarting se produit lorsque l'utilisateur enlève tous les doigts de l'écran. Le code définit la rapidité initiale et la décélération pour le déplacement, l'expansion et la rotation du rectangle.

    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
    
    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;
    }
    
  7. Générez et exécutez le projet.

    Vous devez 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 reproduire plusieurs des manipulations suivantes de manière simultanée.

  • Pour déplacer le Rectangle, mettez un doigt sur le Rectangle et déplacez le doigt au travers de l'écran.

  • Pour redimensionner le Rectangle, mettez deux doigts sur le Rectangle et déplacez ensemble les doigts l'un vers l'autre, ou en les éloignant l'un de l'autre.

  • Pour faire pivoter le Rectangle, mettez deux doigts sur le Rectangle et faites les pivoter l'un autour de l'autre.

Pour provoquer l'inertie, enlevez rapidement vos doigts de l'écran lorsque vous exécutez les manipulations précédentes. Le déplacement, le redimensionnement ou la rotation du Rectangle auront lieu pendant encore quelques secondes avant de s'arrêter.

Voir aussi

Référence

UIElement.ManipulationStarting

UIElement.ManipulationDelta

UIElement.ManipulationInertiaStarting