本文介绍如何使用 .NET 多平台应用 UI (.NET MAUI) IDeviceDisplay 接口读取有关设备的屏幕指标的信息。 此界面可用于请求屏幕在应用运行时保持清醒状态。
IDeviceDisplay接口的默认实现通过DeviceDisplay.Current属性提供。
IDeviceDisplay 接口和 DeviceDisplay 类都包含在 Microsoft.Maui.Devices 命名空间中。
主显示信息
该 MainDisplayInfo 属性返回有关屏幕和方向的信息。 下面的代码示例使用 Loaded 页面的事件来读取有关当前屏幕的信息:
private void ReadDeviceDisplay()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine($"Pixel width: {DeviceDisplay.Current.MainDisplayInfo.Width} / Pixel Height: {DeviceDisplay.Current.MainDisplayInfo.Height}");
sb.AppendLine($"Density: {DeviceDisplay.Current.MainDisplayInfo.Density}");
sb.AppendLine($"Orientation: {DeviceDisplay.Current.MainDisplayInfo.Orientation}");
sb.AppendLine($"Rotation: {DeviceDisplay.Current.MainDisplayInfo.Rotation}");
sb.AppendLine($"Refresh Rate: {DeviceDisplay.Current.MainDisplayInfo.RefreshRate}");
DisplayDetailsLabel.Text = sb.ToString();
}
该 IDeviceDisplay 接口还提供 MainDisplayInfoChanged 事件,此事件会在任何屏幕指标发生更改时触发,例如当设备方向从 DisplayOrientation.Landscape 更改为 DisplayOrientation.Portrait 时。
使屏幕保持打开状态
还可以通过将属性设置为 KeepScreenOntrue 来阻止设备锁定或者屏幕关闭。 以下代码示例在按下开关控件时切换屏幕锁:
private void AlwaysOnSwitch_Toggled(object sender, ToggledEventArgs e) =>
DeviceDisplay.Current.KeepScreenOn = AlwaysOnSwitch.IsToggled;
平台差异
本部分介绍特定于平台的设备显示差异。
- Android
- iOS/Mac Catalyst
- Windows操作系统
没有平台差异。
浏览示例