admin 发表于 2023-10-21 09:21:56

【C#】NET MAUI读取不同设备信息

如何使用 .NET 多平台应用 UI (.NET MAUI) IDeviceInfo 接口来读取有关运行应用的设备的信息。

using Microsoft.Maui.Devices;

private string ReadDeviceInfo()
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder();

    sb.AppendLine($"Model: {DeviceInfo.Current.Model},");
    sb.AppendLine($"Manufacturer: {DeviceInfo.Current.Manufacturer},");
    sb.AppendLine($"Name: {DeviceInfo.Current.Name},");
    sb.AppendLine($"OS Version: {DeviceInfo.Current.VersionString},");
    sb.AppendLine($"Idiom: {DeviceInfo.Current.Idiom},");
    sb.AppendLine($"Platform: {DeviceInfo.Current.Platform},");

    bool isVirtual = DeviceInfo.Current.DeviceType switch
    {
      DeviceType.Physical => false,
      DeviceType.Virtual => true,
      _ => false
    };

    sb.AppendLine($"Virtual device? {isVirtual}");

    return sb.ToString();
}
当前系统:

Model: HP Pavilion Notebook,

Manufacturer: HP,

Name: STUDIO,

OS Version: 10.0.22000.65,

Idiom: Desktop,

Platform: WinUI,

Virtual device? False,

Platform: WinUI


获取设备平台

属性 IDeviceInfo.Platform 表示运行应用的操作系统。 类型 DevicePlatform 为每个操作系统提供属性:

DevicePlatform.Android

DevicePlatform.iOS

DevicePlatform.macOS

DevicePlatform.MacCatalyst

DevicePlatform.tvOS

DevicePlatform.Tizen

DevicePlatform.WinUI

DevicePlatform.watchOS

DevicePlatform.Unknown

以下示例演示如何检查 属性是否 IDeviceInfo.Platform 与操作系统匹配 Android :

private bool IsAndroid() => DeviceInfo.Current.Platform == DevicePlatform.Android;



获取设备类型

属性 IDeviceInfo.Idiom 表示运行应用的设备类型,例如台式计算机或平板电脑。 类型 DeviceIdiom 为每种类型的设备提供属性:

DeviceIdiom.Phone

DeviceIdiom.Tablet

DeviceIdiom.Desktop

DeviceIdiom.TV

DeviceIdiom.Watch

DeviceIdiom.Unknown

以下示例演示如何将 IDeviceInfo.Idiom 值与 DeviceIdiom 属性进行比较:

private void PrintIdiom()
{
    if (DeviceInfo.Current.Idiom == DeviceIdiom.Desktop)
      Console.WriteLine("The current device is a desktop");
    else if (DeviceInfo.Current.Idiom == DeviceIdiom.Phone)
      Console.WriteLine("The current device is a phone");
    else if (DeviceInfo.Current.Idiom == DeviceIdiom.Tablet)
      Console.WriteLine("The current device is a Tablet");
}



设备类型

IDeviceInfo.DeviceType 属性 一个枚举,用于确定应用程序是在物理设备还是虚拟设备上运行。 虚拟设备是指模拟器或仿真程序。

bool isVirtual = DeviceInfo.Current.DeviceType switch
{
    DeviceType.Physical => false,
    DeviceType.Virtual => true,
    _ => false
};



有了以上工具,开发多设备通用的系统就易如反掌了。
页: [1]
查看完整版本: 【C#】NET MAUI读取不同设备信息