首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 系統資訊存取:套件、系統、硬體、PnP 與裝置資訊完整指南

     編輯:關於.NET

前言

Windows 8 應用程式可透過多種 API 取得套件身分、作業系統版本、硬體識別碼、即插即用裝置列表以及常用裝置 (如攝影機、印表機、可攜式裝置) 的詳細資訊。本文彙整五大資訊類別的存取方式與完整程式碼範例。

一、取得應用程式套件資訊

Package.Current.Id 提供名稱、版本、架構、發行者、完整名稱、系列名稱、安裝路徑等屬性。

程式碼範例

using System;
using Windows.ApplicationModel;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Information
{
    public sealed partial class PackageInfo : Page
    {
        public PackageInfo()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            Package package = Package.Current;
            PackageId packageId = package.Id;
            lblMsg.Text = "Name: " + packageId.Name;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Version: " + packageId.Version;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Architecture: " + packageId.Architecture;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Publisher: " + packageId.Publisher;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "PublisherId: " + packageId.PublisherId;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FullName: " + packageId.FullName;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FamilyName: " + packageId.FamilyName;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Installed Location Path: " + package.InstalledLocation.Path;
        }
    }
}

二、取得系統相關資訊

CPU 核心數 (Environment.ProcessorCount)、系統啟動時間 (Environment.TickCount)、目前文化特性 (CultureInfo.CurrentCulture)、目前時間與時區、Windows 版本號 (透過 PnP 根容器查詢 HAL 裝置驅動程式版本)。

程式碼範例

using System;
using System.Globalization;
using System.Threading.Tasks;
using Windows.Devices.Enumeration.Pnp;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Linq;

namespace XamlDemo.Information
{
    public sealed partial class SystemInfo : Page
    {
        public SystemInfo()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            lblMsg.Text += "CPU 核心數量:" + Environment.ProcessorCount.ToString();
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "系統自上次啟動以來所經過的毫秒數:" + Environment.TickCount;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "目前語言:" + CultureInfo.CurrentCulture.DisplayName;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "目前時間:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + " 星期" + "日一二三四五六七".Substring((int)DateTime.Now.DayOfWeek, 1);
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "目前時區:" + "UTC" + DateTimeOffset.Now.ToString("%K");
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "目前系統版本號:" + (await GetWindowsVersionAsync()).ToString();
        }

        #region 取得目前系統版本號
        public static async Task<string> GetWindowsVersionAsync()
        {
            var hal = await GetHalDevice(DeviceDriverVersionKey);
            if (hal == null || !hal.Properties.ContainsKey(DeviceDriverVersionKey)) return null;
            var versionParts = hal.Properties[DeviceDriverVersionKey].ToString().Split('.');
            return string.Join(".", versionParts.Take(2).ToArray());
        }

        private static async Task<PnpObject> GetHalDevice(params string[] properties)
        {
            var actualProperties = properties.Concat(new[] { DeviceClassKey });
            var rootDevices = await PnpObject.FindAllAsync(PnpObjectType.Device, actualProperties, RootQuery);
            foreach (var rootDevice in rootDevices.Where(d => d.Properties != null && d.Properties.Any()))
            {
                var lastProperty = rootDevice.Properties.Last();
                if (lastProperty.Value != null)
                    if (lastProperty.Value.ToString().Equals(HalDeviceClass))
                        return rootDevice;
            }
            return null;
        }

        const string DeviceClassKey = "{A45C254E-DF1C-4EFD-8020-67D146A850E0},10";
        const string DeviceDriverVersionKey = "{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3";
        const string RootContainer = "{00000000-0000-0000-FFFF-FFFFFFFFFFFF}";
        const string RootQuery = "System.Devices.ContainerId:=\"" + RootContainer + "\"";
        const string HalDeviceClass = "4d36e966-e325-11ce-bfc1-08002be10318";
        #endregion
    }
}

三、取得硬體識別資訊

HardwareIdentification.GetPackageSpecificToken(null) 回傳 HardwareToken,包含 Id (硬體識別碼)、Signature (簽名)、Certificate (憑證),均為 IBuffer,可轉 Base64 字串儲存或傳輸。

程式碼範例

using System;
using Windows.Storage.Streams;
using Windows.System.Profile;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Information
{
    public sealed partial class HardwareInfo : Page
    {
        public HardwareInfo()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            HardwareToken hardwareToken = HardwareIdentification.GetPackageSpecificToken(null);
            lblMsg.Text = "Id: " + Buffer2Base64(hardwareToken.Id);
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Signature: " + Buffer2Base64(hardwareToken.Signature);
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Certificate: " + Buffer2Base64(hardwareToken.Certificate);
        }

        private string Buffer2Base64(IBuffer buffer)
        {
            using (var dataReader = DataReader.FromBuffer(buffer))
            {
                try
                {
                    var bytes = new byte[buffer.Length];
                    dataReader.ReadBytes(bytes);
                    return Convert.ToBase64String(bytes);
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
        }
    }
}

四、取得 PnP (即插即用) 裝置資訊

PnpObject.FindAllAsync 可列舉裝置容器、裝置、裝置介面等類型,指定屬性鍵 (如 System.ItemNameDisplay、System.Devices.Manufacturer、System.Devices.ModelName、System.Devices.Connected) 取得詳細資訊。

XAML 介面

<Page x:Class="XamlDemo.Information.PnpObjectInfo" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Information" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<Grid Margin="120 0 0 0">
<ListBox x:Name="listBox" Margin="0 0 10 10">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock FontWeight="Bold" Text="{Binding Name}" />
<TextBlock Text="{Binding Id}" />
<TextBlock Text="{Binding Properties}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Page>

程式碼後置

using System;
using Windows.Devices.Enumeration.Pnp;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Information
{
    public sealed partial class PnpObjectInfo : Page
    {
        public PnpObjectInfo()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            listBox.Items.Clear();
            string[] properties = { "System.ItemNameDisplay", "System.Devices.Manufacturer", "System.Devices.ModelName", "System.Devices.Connected" };
            var containers = await PnpObject.FindAllAsync(PnpObjectType.DeviceContainer, properties);
            foreach (PnpObject container in containers)
            {
                listBox.Items.Add(new DisplayItem(container));
            }
        }

        class DisplayItem
        {
            public string Id { get; private set; }
            public string Name { get; private set; }
            public string Properties { get; private set; }
            public DisplayItem(PnpObject container)
            {
                Name = (string)container.Properties["System.ItemNameDisplay"];
                if (string.IsNullOrWhiteSpace(Name)) Name = "未知";
                Id = "Id: " + container.Id;
                foreach (var property in container.Properties)
                {
                    Properties += property.Key + " = " + property.Value + "\n";
                }
            }
        }
    }
}

五、取得常用裝置資訊

DeviceInformation.FindAllAsync 依裝置類別 GUID (如可攜式裝置 {6AC27878-A6FA-4155-BA85-F98F491D4F33}) 或 DeviceClass 列舉 (如 AudioRender) 篩選裝置。可取得裝置名稱、ID、啟用狀態、縮略圖 (256x256) 與圖示 (48x48)。DeviceWatcher 可即時監聽裝置新增/移除/更新事件。

XAML 介面

<Page x:Class="XamlDemo.Information.DeviceInfo" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Information" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid Background="Transparent">
<Grid Margin="120 0 0 0">
<ListBox x:Name="listBox" Margin="0 0 10 10">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0 0 0 20">
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}" />
<TextBlock Text="{Binding Path=Id}" />
<TextBlock Text="{Binding Path=IsEnabled}" />
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="裝置縮略圖:" />
<Image Width="256" Height="256" Source="{Binding Path=Thumbnail}" Margin="10 0 0 0" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" Text="裝置圖示:" />
<StackPanel Background="Blue" Margin="10 0 0 0">
<Image Width="48" Height="48" Source="{Binding Path=GlyphThumbnail}" />
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
</Page>

程式碼後置

using System;
using Windows.Devices.Enumeration;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Information
{
    public sealed partial class DeviceInfo : Page
    {
        public DeviceInfo()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            listBox.Items.Clear();
            var interfaces = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{6AC27878-A6FA-4155-BA85-F98F491D4F33}\"", null);
            foreach (DeviceInformation deviceInterface in interfaces)
            {
                DeviceThumbnail thumbnail = await deviceInterface.GetThumbnailAsync();
                DeviceThumbnail glyph = await deviceInterface.GetGlyphThumbnailAsync();
                listBox.Items.Add(new DisplayItem(deviceInterface, thumbnail, glyph));
            }
            DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher();
        }

        class DisplayItem
        {
            public string Name { get; private set; }
            public string Id { get; private set; }
            public string IsEnabled { get; private set; }
            public BitmapImage Thumbnail { get; private set; }
            public BitmapImage GlyphThumbnail { get; private set; }
            public DisplayItem(DeviceInformation deviceInterface, DeviceThumbnail thumbnail, DeviceThumbnail glyph)
            {
                Name = (string)deviceInterface.Properties["System.ItemNameDisplay"];
                Id = "ID: " + deviceInterface.Id;
                IsEnabled = "IsEnabled: " + deviceInterface.IsEnabled;
                Thumbnail = new BitmapImage();
                Thumbnail.SetSource(thumbnail);
                GlyphThumbnail = new BitmapImage();
                GlyphThumbnail.SetSource(glyph);
            }
        }
    }
}

總結

  • 套件資訊用於授權驗證、版本顯示、資料隔離。
  • 系統資訊適合診斷、日誌、相容性判斷。
  • 硬體 Token 可作為裝置指紋,支援離線授權、防作弊。
  • PnP 列舉提供完整硬體清單,適合驅動程式管理、硬體偵測工具。
  • 常用裝置 API 專注使用者可感知裝置 (影音、儲存、攝影),支援 UI 豐富呈現與即時監聽。

[原始碼下載]:https://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved