Compartilhar via


Como: Alça de rotação de tela

Você pode desenvolver aplicativos Direct3D para orientações de tela diferentes de retrato.Entretanto, drivers do dispositivo fornecem níveis variáveis de suporte para processamento em uma orientação que não seja a de retrato, assim o aplicativo deve seguir práticas recomendadas para manipular rotação de tela.

Observação:

Aplicativos móveis de Direct3D gerenciado requerem software Windows Mobile versão 5.0 para Pocket PCs e Smartphones .Consulte Recursos externos para o .NET Compact Framework Para obter informações sobre o software Windows Mobile e SDKs.

Os exemplos de código a seguir são no Windows Software Development Kit (SDK).

Para detectar se uma tela está em um estado rotacionado

  1. Adicionar uma referência para o Microsoft.WindowsCE.Forms componente para seu projeto.

  2. A maneira mais fácil para adicionar código de detecção é colocá-lo do formulário principal Resize evento manipulador. Adicione um delegado para o manipulador de eventos no construtor do formulário.

    this.Resize += new System.EventHandler(this.MyForm_Resize);
    
    AddHandler Resize, AddressOf Me.MyForm_Resize
    
  3. Adicionar o booliano orientationChanged variável de membro da classe que irá controlar quando a orientação é alterada. Usar o valor do ScreenOrientation propriedade para determinar a orientação corrente. Um valor de Angle0 indica modo retrato. Se a orientação corrente é diferente disso, tome nota pelo configuração o orientationChanged sinalizar. Normalmente, nenhuma ação é tomada neste momento pois o aplicativo pode estar em segundo plano.Não altere a orientação programaticamente aqui porque a alteração de orientação que disparou o evento de redimensionar provavelmente não foi concluída ainda.Se você tentar alterar a orientação de volta agora ela falhará.

        // 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
    

Como executar ação quando a tela é rotacionada

  • Você pode verificar cada quadro para determinar se a orientação foi alterada.The CheckRotation método no exemplo de código a seguir altera a orientação da tela para o modo retrato, definindo o ScreenOrientation propriedade. Considere a possibilidade de fazer outras providências de acordo com a experiência do usuário desejado.Por exemplo, talvez você não deseja que o aplicativo para alterar a orientação de tela sozinho, mas em vez disso notifique o usuário que o renderização não continuará a menos que o usuário a altere novamente.Se você alterar a orientação da tela, você também deve salvar e restauração a orientação da tela inicial, conforme mostrado no exemplo a seguir.Se você não altere a orientação da tela, mas em vez disso executar alguma Outros ação, o renderização pode continuar normalmente, ele pode falhar silenciosamente, ou pode falhar retornando uma exceção.

    O exemplo de código a seguir tenta colocar o dispositivo no modo de orientação retrato, se ele ainda não estiver no modo retrato.The CheckOrientation método retorna true Se o dispositivo estiver no modo retrato.

    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 a orientação quando o aplicativo termina

  • Se você decidir alterar a orientação de tela programaticamente, você também deve restaurar a orientação inicial do aplicativo quando seu aplicativo terminar.Porque um aplicativo pode tentar alterar a orientação durante a execução, você precisa salvar a orientação inicial e restaurá-la quando o aplicativo termina.Adicione uma variável de membro para armazenar a orientação inicial.

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

    Adicione isto ao final do método Main para tentar restaurar a orientação quando o aplicativo termina.

    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
    

Consulte também

Conceitos

Tópicos "como" do .NET compact estrutura

Outros recursos

Exemplo de matrizes Mobile Direct3D

Programação Direct3D móvel no .NET Compact estrutura