裝置顯示資訊

Browse sample. 流覽範例

本文說明如何使用 .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;

平台差異

本節說明裝置顯示器的平臺特定差異。

無平台差異。