简体   繁体   English

如何检测屏幕方向

[英]How to detect screen orientation

I am trying differenciate between the device being in Landscape or Portrait mode. 我正在尝试区分处于横向或纵向模式的设备。 180° rotations don't matter to me, just which side is longer. 180°旋转对我来说并不重要,只是哪一侧更长。

I have tried 我努力了

SimpleOrientation OReading = SimpleOrientationSensor.GetDefault().GetCurrentOrientation();

if(OReading == SimpleOrientation.NotRotated || OReading == SimpleOrientation.Rotated180DegreesCounterclockwise)
    ApplicationData.Current.LocalSettings.Values["Orientation"] = "Landscape";
if (OReading == SimpleOrientation.Rotated90DegreesCounterclockwise || OReading == SimpleOrientation.Rotated270DegreesCounterclockwise)
    ApplicationData.Current.LocalSettings.Values["Orientation"] = "Portrait";

but the first line already throws a NullReferenceException. 但第一行已经引发了NullReferenceException。 What would be the correct way to do this? 正确的方法是什么?

I have a .NET component that could technically also perform this, but I would prefer to do it in UWP if possible. 我有一个.NET组件,从技术上讲,它也可以执行此操作,但如果可能的话,我希望在UWP中执行。

Note that I am not running in a simulator, but launching the App on a device that supports rotation. 请注意,我不是在模拟器中运行,而是在支持旋转的设备上启动应用程序。

I actually don't need the sensor data though, I just want to know how the screen orientation is, which can be different from the sensor data. 我实际上不需要传感器数据,我只想知道屏幕方向如何,这可能与传感器数据不同。

Edit: 编辑:

public async void ChangedAsync(AppResourceGroupInfoWatcher sender, AppResourceGroupInfoWatcherExecutionStateChangedEventArgs args)
{
    DisplayInformation current = DisplayInformation.GetForCurrentView();

This also does not work, and in UWP it gives me the crash 这也不起作用,在UWP中它使我崩溃

Windows.Graphics.Display: GetForCurrentView must be called on a thread that is associated with a CoreWindow. Windows.Graphics.Display:必须在与CoreWindow关联的线程上调用GetForCurrentView。

The function is getting called by an AppResourceGroupInfoWatcher. 该函数正在由AppResourceGroupInfoWatcher调用。

I am using: 我在用:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Metadata;
using Windows.Graphics.Display;
using Windows.Storage;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

targeting version 1803 定位版本1803

This should work. 这应该工作。

bool isInLandscapeMode = 
Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Orientation == 
Windows.UI.ViewManagement.ApplicationViewOrientation.Landscape;

ApplicationData.Current.LocalSettings.Values["Orientation"] = isInLandscapeMode ? 
"Landscape" : "Portrait";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM