How to detect screen orientation from a Direct3D app for Windows Phone 8
May 03, 2013
Applies to: Windows Phone 8 only
This topic shows you how to determine the orientation of the phone from a Windows Phone Direct3D app. You can use the sensor APIs to determine the orientation of the phone, which is useful for augmented reality apps and games, but is overly complicated and expensive if all you are interested in is whether the phone is in portrait or landscape mode. Instead, your app can query the CurrentOrientation property of the DisplayProperties class to get the current orientation of the phone. The value returned is a member of the DisplayOrientations enumeration that indicates if the phone is in the portrait, landscape, portrait flipped, or landscape flipped orientation. You can also specify which of these orientations your app supports by setting the AutoRotationPreferences property to one or more of these enumeration values, combined with the or operator.
If you check the current orientation after your app has been running for a short while, the value of CurrentOrientation will be accurate. However, when your app is first launched, the time it takes for the accelerometer to start and for the OS to determine the orientation can vary, so it is a good idea to subscribe to the OrientationChanged event. This event will be triggered when the phone moves into any of the orientations you specified when setting AutoRotationPreferences. If the user launches your app with the phone already in an orientation other than portrait, and you have included this orientation in your auto rotation preferences, the event will be raised when your app launches. Of course, you can also use this event if you want to be alerted to orientation changes as your app runs.
Detecting orientation changes
Create a new Direct3D project. This example assumes you name the project “NativeFundamentals”.
In the NativeFundamentals.h header file, declare the handler for the OrientationChanged event. Also, declare a member variable to store the current orientation.
At the top of the NativeFundamentals.cpp file, add a using directive to include the Windows.Graphics.Display namespace.
In the OnActivated method in NativFundamentals.cpp, set the member variable to DisplayOrientations::Portrait. This is the default orientation. If the phone is in this orientation, OrientationChanged will not be raised.
Next, in OnActivated, set the orientations your app supports. OrientationChanged will only be raised when the phone moves into orientations you set using this property.
Again in OnActivated, hook up the event handler you declared to the OrientationChanged event.
Finally, in NativeFundamentals.cpp, implement the event handler by checking the CurrentOrientation property.