Quickstart: Determining device orientation with the SimpleOrientation sensor (C++)

You can use the SimpleOrientation sensor to determine device orientation with an app written in C#.

Apps use the SimpleOrientation sensor to determine the current device orientation (portrait up, portrait down, landscape left, landscape right) as well as the device's face-up or face-down status.

Rather than returning properties like "portrait up" or "landscape left", this sensor returns a rotation value: "Not rotated", "Rotated90DegreesCounterclockwise", and so on. The following table maps common orientation properties to the corresponding sensor reading.

Orientation Corresponding sensor reading
Portrait Up NotRotated
Landscape Left Rotated90DegreesCounterclockwise
Portrait Down Rotated180DegreesCounterclockwise
Landscape Right Rotated270DegreesCounterclockwise

 

Objective: After completing this quickstart you will understand how to use the SimpleOrientation sensor to detect changes in movement and face-up or face-down status.

Prerequisites

You should be familiar with XAML, Visual C#, and events.

The device or emulator that you're using must support an accelerometer.

Time to complete: 25 minutes.

Instructions

1. Open Microsoft Visual Studio

Open an instance of Microsoft Visual Studio.

2. Create a new project

Create a new project, choosing a Blank App from the Visual C++/Store Apps project types.

3. Replace the header file contents

Open your project's MainPage.xaml.h file and replace the existing comments, code, and definitions with the following.

//
// MainPage.xaml.h
// Declaration of the MainPage.xaml class.
//

#pragma once


#include "MainPage.g.h"

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public ref class MainPage sealed
    {
    public:
        MainPage();

    private:
        void OrientationChanged(Windows::Devices::Sensors::SimpleOrientationSensor^ sender, Windows::Devices::Sensors::SimpleOrientationSensorOrientationChangedEventArgs^ e);
        void DisplayOrientation(Windows::Devices::Sensors::SimpleOrientation orientation);

        Windows::Devices::Sensors::SimpleOrientationSensor^ sensor;
        Windows::Foundation::EventRegistrationToken listenerToken;

    protected:
        virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
    };
}

You'll need to replace the class name in the previous snippet with the name of your app's class. For example, if you created a project named SimpleOrientationCPP, you'd replace namespace App1 with namespace SimpleOrientationCPP.

4. Replace the C++ code

Open your project's MainPage.xaml.cpp file and replace the existing code with the following.

//
// MainPage.xaml.cpp
// Implementation of the MainPage.xaml class.
//

#include "pch.h"
#include "MainPage.xaml.h"

using namespace App1;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

// Below namespaces are required to support sensors and events
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Platform;
using namespace Windows::Devices::Sensors;
using namespace Windows::UI::Core;


// The Blank Page item template is documented at https://go.microsoft.com/fwlink/p/?linkid=234238

MainPage::MainPage()
{
    InitializeComponent();

    sensor = SimpleOrientationSensor::GetDefault();

    if (sensor != nullptr)
    {
        listenerToken = sensor->OrientationChanged::add(ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &MainPage::OrientationChanged));
    }
}

void MainPage::DisplayOrientation(SimpleOrientation orientation)
{
    switch (orientation)
    {
        case SimpleOrientation::NotRotated:
            txtOrientation->Text = "Not Rotated";
            break;
        case SimpleOrientation::Rotated90DegreesCounterclockwise:
            txtOrientation->Text = "Rotated 90 Degrees Counterclockwise";
            break;
        case SimpleOrientation::Rotated180DegreesCounterclockwise:
            txtOrientation->Text = "Rotated 180 Degrees Counterclockwise";
            break;
        case SimpleOrientation::Rotated270DegreesCounterclockwise:
            txtOrientation->Text = "Rotated 270 Degrees Counterclockwise";
            break;
        case SimpleOrientation::Faceup:
            txtOrientation->Text = "Faceup";
            break;
        case SimpleOrientation::Facedown:
            txtOrientation->Text = "Facedown";
            break;
        default:
            txtOrientation->Text = "Unknown orientation";
            break;
    }
}

void MainPage::OrientationChanged(SimpleOrientationSensor^ /* sender */, SimpleOrientationSensorOrientationChangedEventArgs^ e)
{
    auto ignored = Dispatcher->RunAsync(
        CoreDispatcherPriority::Normal,
        ref new DispatchedHandler(
            [this, e]()
            {
                DisplayOrientation(e->Orientation );
            },
            CallbackContext::Any
            )
        );
}

/// <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>
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
}

You'll need to rename the namespace in the previous snippet with the name you gave your project. For example, if you created a project named SimpleOrientationCS, you'd replace using namespace App1; with using namespace SimpleOrientationCPP;.

5. Replace the XAML code

Open the file MainPage.xaml and copy the following XML into this file (replacing its original contents).

<Page
    x:Class="SimpleOrientationCPP.MainPage"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SimpleOrientationCPP"
    xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
        <TextBlock HorizontalAlignment="Left" Height="24" Margin="8,8,0,0" TextWrapping="Wrap" Text="Current Orientation:" VerticalAlignment="Top" Width="101" Foreground="#FFF8F7F7"/>
        <TextBlock x:Name="txtOrientation" HorizontalAlignment="Left" Height="24" Margin="118,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="175" Foreground="#FFFEFAFA"/>

    </Grid>
</Page>

You'll need to replace the first part of the class name in the previous snippet with the namespace of your app. For example, if you created a project named SimpleOrientationCPP, you'd replace x:Class="App1.MainPage" with x:Class="SimpleOrientationCPP.MainPage". You should also replace xmlns:local="using:App1" with xmlns:local="using:SimpleOrientationCPP".

6. Build, deploy and run the app

Press F5 or select Debug > Start Debugging to build, deploy, and run the app.

Once the app is running, you can change the accelerometer values by moving the device or using the emulator tools.

7. Stop the app

  1. Press ALT+Tab to return to Visual Studio.
  2. Press Shift+F5 or select Debug > Stop Debugging to stop the app.

Summary

The previous example demonstrates how little code you'll need to write in order to integrate simple-orientation sensor input in your app.

The app establishes a connection with the default sensor in the MainPage constructor.

sensor = SimpleOrientationSensor::GetDefault();

The new sensor data is captured in the OrientationChanged method. Each time the sensor driver receives new data from the sensor, it passes the values to your app using this event handler. The app registers this event handler on the following line.

listenerToken = sensor->OrientationChanged::add(ref new TypedEventHandler
<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>
(this, &MainPage::OrientationChanged));
 

These new values are written to a TextBlock found in the project's XAML.

        <TextBlock HorizontalAlignment="Left" Height="24" Margin="8,8,0,0" TextWrapping="Wrap" Text="Current Orientation:" VerticalAlignment="Top" Width="101" Foreground="#FFF8F7F7"/>
        <TextBlock x:Name="txtOrientation" HorizontalAlignment="Left" Height="24" Margin="118,8,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Width="175" Foreground="#FFFEFAFA"/>

SimpleOrientation Sensor class

SimpleOrientation Sensor Sample

Roadmap for creating apps using C#, C++, or VB