拓冰建站拓冰建站
首页 / 资讯中心 / 正文

Windows-universal-samples 之 SimpleOrientationSensor 示例:UWP 简易方向传感器的事件与轮询实战

示例工程【免费下载链接】Windows-universal-samplesAPI samples for the Universal Windows Platform.项目地址https://gitcode.com/gh_mirrors/wi/Windows-universal-samples点击查看免费下载本指南以 Windows-universal-samples 仓库中的 SimpleOrientationSensor 示例 为核心系统讲解 UWP 应用如何通过Windows.Devices.Sensors.SimpleOrientationSensor类获取设备简易方向未旋转、面朝上、逆时针旋转 90 度等。文中不仅完整还原官方示例的构建与运行步骤还结合仓库内 C# 与 C/CX 双语言源码深入剖析数据事件监听与轮询读取两种场景的完整实现、UI 线程调度与可见性处理细节帮助读者直接套用并二次开发自己的方向感应功能。示例概览与核心 APISimpleOrientationSensor简易方向传感器与需要三轴数据的 OrientationSensor 不同它返回的是离散的六个方向状态非常适合实现旋转屏幕提示设备翻转检测这类轻量级需求。本示例位于仓库的 Samples/SimpleOrientationSensor 目录官方描述为Shows how to use the Windows.Devices.Sensors.SimpleOrientationSensor class for a simple device orientation sensor.示例允许用户实时查看设备简易方向值并提供两种可选场景Orientation sensor data events数据事件注册OrientationChanged事件监听传感器方向变化时实时推送更新Polling orientation sensor readings轮询读取手动调用GetCurrentOrientation()获取当前方向快照。核心 API 位于Windows.Devices.Sensors命名空间关键成员如下成员类型说明SimpleOrientationSensor.GetDefault()静态方法获取系统默认方向传感器实例设备不支持时返回nullOrientationChanged事件方向变化时触发事件参数为SimpleOrientationSensorOrientationChangedEventArgs其Orientation属性携带新方向GetCurrentOrientation()方法同步读取当前方向轮询场景使用方向枚举SimpleOrientation的取值可从源码中的DisplayOrientation辅助方法Scenario1_DataEvents.xaml.cs完整看到NotRotated——未旋转Rotated90DegreesCounterclockwise——逆时针旋转 90 度Rotated180DegreesCounterclockwise——逆时针旋转 180 度Rotated270DegreesCounterclockwise——逆时针旋转 270 度Faceup——面朝上Facedown——面朝下其他情况统一显示为Unknown orientation。工程结构与双语言实现示例按语言分为两个独立子工程均包含相同的两个场景页面Samples/SimpleOrientationSensor/ ├── cpp/ # C/CXWindows Runtime C版本 │ ├── Scenario1_DataEvents.xaml / .cpp / .h │ ├── Scenario2_Polling.xaml / .cpp / .h │ ├── SampleConfiguration.h / .cpp │ ├── SimpleOrientationSensor.sln / .vcxproj │ └── Package.appxmanifest └── cs/ # C# 版本 ├── Scenario1_DataEvents.xaml / .xaml.cs ├── Scenario2_Polling.xaml / .xaml.cs ├── SampleConfiguration.cs ├── SimpleOrientationSensor.sln / .csproj └── Package.appxmanifest两个语言版本的场景入口由 SampleConfiguration.csC 侧对应SampleConfiguration.h/.cpp统一注册public const string FEATURE_NAME Simple Orientation Sensor; ListScenario scenarios new ListScenario { new Scenario() { Title Data Events, ClassType typeof(SimpleOrientationCS.Scenario1_DataEvents) }, new Scenario() { Title Polling, ClassType typeof(SimpleOrientationCS.Scenario2_Polling) } };清单文件 Package.appxmanifest 声明了Windows.Universal目标设备家族MinVersion为10.0.10240.0、MaxVersionTested为10.0.22621.0即面向 Windows 10 及以上版本的通用应用。场景一数据事件Data Events数据事件场景的界面Scenario1_DataEvents.xaml包含Enable / Disable两个按钮与一个方向输出TextBlock其说明文字为Registers an event listener for orientation changes and displays the new orientation as it is reported.获取传感器实例页面构造函数中调用静态工厂方法获取默认传感器并处理设备不支持的情况Scenario1_DataEvents.xaml.csprivate SimpleOrientationSensor _sensor; public Scenario1_DataEvents() { this.InitializeComponent(); _sensor SimpleOrientationSensor.GetDefault(); if (_sensor null) { rootPage.NotifyUser(No simple orientation sensor found, NotifyType.ErrorMessage); } }这是所有 UWP 传感器用法的标准模式先判空再使用。在没有方向传感器的设备如部分模拟器或台式机上运行会得到明确错误提示。注册与注销事件点击 Enable 后注册事件并立即显示一次当前方向Scenario1_DataEvents.xaml.csprivate void ScenarioEnable(object sender, RoutedEventArgs e) { if (_sensor ! null) { Window.Current.VisibilityChanged new WindowVisibilityChangedEventHandler(VisibilityChanged); _sensor.OrientationChanged new TypedEventHandlerSimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs(OrientationChanged); ScenarioEnableButton.IsEnabled false; ScenarioDisableButton.IsEnabled true; // Display the current orientation once while waiting for the next orientation change DisplayOrientation(ScenarioOutput_Orientation, _sensor.GetCurrentOrientation()); } else { rootPage.NotifyUser(No simple orientation sensor found, NotifyType.ErrorMessage); } }两个实现细节值得注意注册事件的同时也调用GetCurrentOrientation()事件只在方向变化时触发因此先主动读取一次当前值避免按钮点击后界面一直停留在 No data同时注册Window.Current.VisibilityChanged当应用窗口不可见时注销传感器事件可见时重新注册见 VisibilityChanged 处理。源码注释明确指出不可见时注销事件可避免传感器数据引发非预期操作恢复可见后无需手动恢复reportInterval系统在应用恢复时会自动恢复。Disable 按钮反向操作同时注销两类事件并切换按钮可用状态Scenario1_DataEvents.xaml.cs。事件回调与 UI 线程调度OrientationChanged回调运行在后台线程必须通过Dispatcher编组到 UI 线程后才能更新TextBlockScenario1_DataEvents.xaml.csasync private void OrientationChanged(object sender, SimpleOrientationSensorOrientationChangedEventArgs e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () { DisplayOrientation(ScenarioOutput_Orientation, e.Orientation); }); }C/CX 版本实现了完全相同的逻辑Scenario1_DataEvents.xaml.cpp同样通过Dispatcher-RunAsync(CoreDispatcherPriority::Normal, ...)将e-Orientation送回 UI 线程并在头文件 Scenario1_DataEvents.xaml.h 中用EventRegistrationTokenvisibilityToken/orientationToken保存事件句柄以便注销。C 版在OnNavigatedFrom中还会判断NavigationMode::Forward e-Uri nullptr以避免应用挂起Phone 场景时误清理事件。页面生命周期清理离开页面时若传感器事件仍处于启用状态则注销所有事件C# 的OnNavigatingFrom见 Scenario1_DataEvents.xaml.csprotected override void OnNavigatingFrom(NavigatingCancelEventArgs e) { if (ScenarioDisableButton.IsEnabled) { Window.Current.VisibilityChanged - new WindowVisibilityChangedEventHandler(VisibilityChanged); _sensor.OrientationChanged - new TypedEventHandlerSimpleOrientationSensor, SimpleOrientationSensorOrientationChangedEventArgs(OrientationChanged); } base.OnNavigatingFrom(e); }这一模式保证了导航离开后不再有悬挂的传感器回调避免内存泄漏与无效 UI 更新。场景二轮询读取Polling轮询场景的界面Scenario2_Polling.xaml只有一个Get按钮说明文字为Performs a single request to retrieve the current device orientation.其代码极为精简核心逻辑只有一步Scenario2_Polling.xaml.csprivate void ScenarioGet(object sender, RoutedEventArgs e) { if (_sensor ! null) { DisplayOrientation(ScenarioOutput_Orientation, _sensor.GetCurrentOrientation()); } else { rootPage.NotifyUser(No simple orientation sensor found, NotifyType.ErrorMessage); } }GetCurrentOrientation()是同步方法返回SimpleOrientation枚举值不涉及事件注册与线程编组——适合需要按需读取、低功耗的场景。C/CX 版实现完全一致Scenario2_Polling.xaml.cpp。两种场景如何选择维度数据事件Data Events轮询Polling数据获取方式事件驱动方向变化自动推送手动调用GetCurrentOrientation()适用场景实时响应方向变化如自动旋转 UI、翻转检测按需读取一次快照如进入页面时读取初始方向线程要求回调在后台线程需Dispatcher编组到 UI 线程同步调用无线程切换负担资源开销持续监听需在不可见/离开页面时注销无持续监听按需消耗构建与运行系统要求Windows 10 及以上操作系统Visual Studio含 UWP 开发工作负载支持 C# 与 C/CX。构建步骤若通过 ZIP 方式获取示例务必解压整个压缩包而不是只解压单个示例文件夹——整个 Windows-universal-samples 集合共享SharedContent依赖本示例的 frontmatter 中extendedZipContent即声明了SharedContent与LICENSE的关联启动 Visual Studio选择FileOpenProject/Solution在解压目录下进入Samples/SimpleOrientationSensor子文件夹再进入首选语言的子目录cs或cpp双击其中的解决方案文件.sln按CtrlShiftB或选择BuildBuild Solution完成构建。运行与部署仅部署选择BuildDeploy Solution部署并调试运行按F5或选择DebugStart Debugging部署并无调试运行按CtrlF5或选择DebugStart Without Debugging。运行后进入 Simple Orientation Sensor 示例页选择Data Events场景点击 Enable旋转或翻转设备即可看到方向实时刷新选择Polling场景点击 Get则单次读取当前方向。若设备无方向传感器界面会显示 No simple orientation sensor found 错误提示。参考与延伸本示例曾提供 JavaScriptHTML/JS版本现已归档至 archived/SimpleOrientationSensor 目录仓库中还包含传感器家族的其他示例如 OrientationSensor三轴姿态传感器、Accelerometer加速度计、Inclinometer倾角计接口模式与本示例一致GetDefault() 事件/轮询双场景可相互参照公共 UI 模板与共享代码位于 SharedContent/Templates 与 SharedContent/cppC 版示例依赖其中的共享 XAML 与基础设施。赞分享示例工程【免费下载链接】Windows-universal-samplesAPI samples for the Universal Windows Platform.项目地址https://gitcode.com/gh_mirrors/wi/Windows-universal-samples点击查看免费下载相关推荐为什么NonSteamLaunchers是Steam Deck玩家必备的终极游戏整合工具为什么NonSteamLaunchers是Steam Deck玩家必备的终极游戏整合工具 NonSteamLaunchers是一款专为Steam Deck设计示例工程Windows-universal-samples Altimeter 示例全解析UWP 高度计传感器的数据事件与轮询两种实现Windows universal samples Altimeter 示例全解析UWP 高度计传感器的数据事件与轮询两种实现 本指南围绕 Windows u示例工程Qwen Code 接入微信基于 iLink Bot API 的 WeChat 频道完整配置指南Qwen Code 接入微信基于 iLink Bot API 的 WeChat 频道完整配置指南 微信是目前最主流的即时通讯平台之一。Qwen Code 在示例工程上一篇企业级Azure文档自动化AzViz与CI/CD流程集成实践下一篇Ambrose平台详解数据工作流可视化与实时监控的终极解决方案创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门