Share via


Cómo: Controlar la rotación de la pantalla

Actualización: noviembre 2007

Puede desarrollar aplicaciones de Direct3D para orientaciones de pantalla que no sean la vertical. Sin embargo, los controladores de dispositivos proporcionan niveles de compatibilidad que varían para representar una orientación que no sea la vertical. De esta forma, la aplicación debe seguir las prácticas recomendadas para el control de rotación de la pantalla.

Nota:

Las aplicaciones móviles Direct3D administradas requieren el software de Windows Mobile versión 5.0 para dispositivos Pocket PC y Smartphone. Vea Recursos externos de .NET Compact Framework para obtener información sobre el software de Windows Mobile y los SDK.

Los siguientes ejemplos de código están en Kit de desarrollo de software de Windows (SDK).

Para detectar que una pantalla está en estado de rotación

  1. Agregue una referencia al componente Microsoft.WindowsCE.Forms en el proyecto.

  2. La manera más fácil de agregar el código de detección es colocarlo en el controlador de eventos Resize del formulario principal. Agregue un delegado para el controlador de eventos en el constructor de su formulario.

    this.Resize += new System.EventHandler(this.MyForm_Resize);
    
    AddHandler Resize, AddressOf Me.MyForm_Resize
    
  3. Agregue la variable miembro de clase orientationChanged Boolean que efectuará al seguimiento cuando la orientación haya cambiado. Utilice el valor de la propiedad ScreenOrientation para determinar la orientación actual. Un valor de Angle0 indica el modo vertical. Si la orientación actual es distinta, indíquelo estableciendo un marcador orientationChanged. Normalmente, no se emprende ninguna medida en este momento, ya que la aplicación se podría estar ejecutando en segundo plano. No cambie la orientación mediante programación porque el cambio de orientación desencadenado por el cambio de tamaño del evento puede que aún no haya finalizado. Si intenta restablecer la orientación anterior, no podrá.

        // Add a class member variable to
        // store that the orientation has changed.
        bool orientationChanged = false;
    
        private void MyForm_Resize(object sender, EventArgs e)
        {
           if (SystemSettings.ScreenOrientation !=
             ScreenOrientation.Angle0)
            orientationChanged = true;
        }
    
        ' Add a class member variable to
        ' store that the orientation has changed.
        Dim OrientationChanged As Boolean = False
    
    Private Sub MyForm_Resize(ByVal sender As Object, ByVal e As EventArgs)
        If (SystemSettings.ScreenOrientation <> ScreenOrientation.Angle0) Then
           orientationChanged = True
        End If
    End Sub
    

Medidas que se emprenden al rotar la pantalla

  • Puede comprobar cada marco para determinar si ha cambiado la orientación. El método CheckRotation del siguiente ejemplo de código vuelve a establecer la orientación de la pantalla en el modo vertical al establecer la propiedad ScreenOrientation. Debe pensar en emprender otras acciones en función de la experiencia deseada del usuario. Por ejemplo, quizá no desee que la propia aplicación cambie la orientación de la pantalla, sino que notifique al usuario que la representación no continuará hasta que éste la cambie. Si realmente cambia la orientación de la pantalla, también debe guardar y restaurar la orientación inicial de la pantalla, como se muestra en el ejemplo siguiente. Si no cambia la orientación y emprende otras acciones en su lugar, la representación puede continuar normalmente, puede que se produzca un error o que se devuelva una excepción.

    El ejemplo de código siguiente intenta colocar el dispositivo en modo de orientación vertical, si aún no está en modo vertical. El método CheckOrientation devuelve true si el dispositivo está en modo vertical.

    private bool CheckOrientation()
    {
        // orientationChanged is set to true in resize if it is
        // detected that the orientation of the device has changed.
        if (orientationChanged)
        {
          // Attempt to change the display back to portrait mode.
          try
          {
             SystemSettings.ScreenOrientation =
              ScreenOrientation.Angle0;
             // Now that the orientation is back to portrait mode
             // Do not attempt to change it again.
             orientationChanged = false;
           }
          catch (Exception)
          {
             // Failed to change the display mode.
             return false;
          }
        }
        return true;
    }
    
    // Use the CheckOrientation() method before rendering occurs.
    // All rendering for each frame occurs here.
    
    private void Render()
    {
        // If the device is not oriented properly, 
        // some display drivers may not work.
        if (!CheckOrientation())
            return;
            // Rendering code omitted here.
    }
    
    Private Function CheckOrientation() As Boolean
        ' orientationChanged is set to true in resize if it is
        ' detected that the orientation of the device has changed.
        If orientationChanged Then
            ' Attempt to change the display back to portrait mode.
            Try 
                SystemSettings.ScreenOrientation = ScreenOrientation.Angle0
                ' Now that the orientation is back to portrait mode
                ' Do not attempt to change it again.
                orientationChanged = false
            Catch  As Exception
                ' Failed to change the display mode.
                Return false
            End Try
        End If
        Return true
    End Function
    
    ' Use the CheckOrientation() method before rendering occurs.
    ' All rendering for each frame occurs here.
    Private Sub Render()
        ' If the device is not oriented properly, 
        ' some display drivers may not work.
        If Not CheckOrientation Then
            Return
        End If
        ' Rendering code omitted here.
    End Sub
    

Para restaurar la orientación cuando la aplicación se cierra

  • Si decide cambiar la orientación de la pantalla mediante programación, también debe restaurar la orientación inicial de la aplicación cuando ésta se cierre. Puesto que una aplicación podría intentar cambiar la orientación durante la ejecución, será necesario que guarde la orientación inicial y la restaure cuando cierre la aplicación. Agregue una variable miembro para almacenar la orientación inicial.

    ScreenOrientation initialOrientation = SystemSettings.ScreenOrientation;
    
    ScreenOrientation initialOrientation = SystemSettings.ScreenOrientation;
    

    Agregue lo siguiente al final del método Main para intentar restaurar la orientación cuando la aplicación finalice.

    if (SystemSettings.ScreenOrientation != initialOrientation)
    {
        try
        {
           SystemSettings.ScreenOrientation = initialOrientation;
        }
        catch (Exception)
        {
            // Unable to change the orientation back 
            // to the original configuration. 
    
            MessageBox.Show("This sample was unable to set the " +
                "orientation back to the original state.");
        }
    }
    
    If (SystemSettings.ScreenOrientation <> initialOrientation) Then
        Try 
            SystemSettings.ScreenOrientation = initialOrientation
        Catch  As Exception
            ' Unable to change the orientation back 
            ' to the original configuration. 
            MessageBox.Show(("This sample was unable to set the " & _
                "orientation back to the original state."))
        End Try
    End If
    

Vea también

Conceptos

.Temas "Cómo..." de .NET Compact Framework

Otros recursos

Ejemplo Direct3D Mobile Matrices

Programar Mobile Direct3D en .NET Compact Framework