WPF: Доступ к системной информации с помощью WinRT

Фрагмент демонстрации GetSystemInfo:

В прошлой заметке я привёл пример кода для доступа к веб-камере с помощью WPF и Windows Runtime (WinRT).
Сейчас мы получим доступ к информации о системе.

  1. Изменим настройки проекта, указав минимальную версию ОС и .NET:
    ProjectPropertiesApplicationGeneral
    Target framework: .NET 6.0
    Target OS: Windows
    Target OS version: 10.0.17763.0
    Windows Presentation Foundation: Enable WPF for this project.

    GetSystemInfoApp.csproj
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>net6.0-windows10.0.17763.0</TargetFramework>
        <Nullable>enable</Nullable>
        <UseWPF>true</UseWPF>
      </PropertyGroup>
    
    </Project>
  2. Код дизайна окошка:
    MainWindow.xaml
    <Window x:Class="GetSystemInfoApp.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:GetSystemInfoApp"
            mc:Ignorable="d"
            Title="MainWindow" Height="475" Width="800">
        <StackPanel>
            <TextBlock x:Name="SystemInfo"
                       Height="350"
                       TextWrapping="Wrap"
                       TextAlignment="Left"
                       Text="TextBlock"
                       Margin="10,10,10,10"
                       FontSize="14"
                       Background="#FFEFEED6"/>
            <Button Content="Get System Info"
                    Width="200"
                    Height="50"
                    HorizontalAlignment="Center"
                    Click="SystemInfo_Click"/>
        </StackPanel>
    </Window>
    
  3. Логика кнопки:
    MainWindow.xaml.cs
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using Windows.Devices.Display;
    using Windows.Security.Cryptography;
    using Windows.System.Profile;
    
    namespace GetSystemInfoApp
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private async void SystemInfo_Click(object sender, RoutedEventArgs e)
            {
                var sb = new StringBuilder();
    
                // Get System Identifier
                var systemId = SystemIdentification.GetSystemIdForPublisher();
    
                // Get System Identifier Preview OS Flighting Info
                var attrNames = new List<string>() { "DebiceFamily", "OSVersionFull", "FlightRing" };
                var attrData = await AnalyticsInfo.GetSystemPropertiesAsync(attrNames);
    
                // Format output
                sb.Append($"\nSystemId: ({systemId.Source})\n {CryptographicBuffer.EncodeToHexString(systemId.Id).ToUpper().Substring(0, 10)}\n");
                sb.Append("\nWindows Build Info:");
                foreach (KeyValuePair<string, string> attr in attrData)
                {
                    sb.Append($"\n{attr.Key}={attr.Value}");
                }
    
                // Get Info about current DiaplayMonitor
                var devInfoDisplays = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(DisplayMonitor.GetDeviceSelector());
    
                // Query specific values and display them
                sb.Append("\n\nDisplay Info:\n");
                foreach(var devInfo in  devInfoDisplays)
                {
                    var displayMonitor = await DisplayMonitor.FromInterfaceIdAsync(devInfo.Id);
                    sb.Append($" Name:{displayMonitor.DisplayName}\n" +
                        $" DeviceId: {displayMonitor.DeviceId}\n" +
                        $" Connector: {displayMonitor.PhysicalConnector}\n" +
                        $" Size: {displayMonitor.PhysicalSizeInInches}\n");
                }
                SystemInfo.Text = sb.ToString();
            }
        }
    }
  4. После нажатия на кнопку, в окошко программы будет выведена информация о системе (Идентификатор системы, версия ОС, FlightRing, а также информация о мониторе, типе подключения и размере экрана).
    Скриншот информация о системе

    Информация о размере экрана (ширина и высота) хранится в дюймах. Можно конечно её конвертировать в миллиметры, но в данный момент в этом нет необходимости.

     

     



Подписаться
Уведомление о
guest
0 Комментарий
Inline Feedbacks
View all comments