程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Windows 8 Store Apps學習(30) 信息

Windows 8 Store Apps學習(30) 信息

編輯:關於.NET

信息: 獲取包信息, 系統信息, 硬件信息, PnP信息, 常用設備信息

介紹

重新想象 Windows 8 Store Apps 之 信息

獲取包信息

獲取系統信息

獲取硬件信息

獲取即插即用(PnP: Plug and Play)的設備的信息

獲取常用設備信息

示例

1、演示如何獲取 app 的 package 信息

Information/PackageInfo.xaml.cs

/*
 * 演示如何獲取 app 的 package 信息
 */
    
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; // 支持的 cpu 類型(X86, Arm, X64, Neutral(均支持), Unknown)
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Publisher: " + packageId.Publisher; // 發布者
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "PublisherId: " + packageId.PublisherId; // 發布者 id
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FullName: " + packageId.FullName; // 包全名(Name + Version + Architecture + PublisherId)
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "FamilyName: " + packageId.FamilyName; // 包系列名(Name + PublisherId)
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "Installed Location Path: " + package.InstalledLocation.Path; // 包的安裝路徑
        }
    }
}

2、演示如何獲取系統的相關信息

Information/SystemInfo.xaml.cs

/*
 * 演示如何獲取系統的相關信息
 */
    
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 獲取當前系統版本號,摘自:http://attackpattern.com/2013/03/device-information-in-windows-8-store-apps/
        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
    }
}

3、演示如何獲取硬件相關的信息

Information/HardwareInfo.xaml.cs

/*
 * 演示如何獲取硬件相關的信息
 */
    
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); // 硬件 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();
                }
            }
        }
    }
}

4、演示如何獲取即插即用(PnP: Plug and Play)的設備的相關信息

Information/PnpObjectInfo.xaml

<Page
    x:Class="XamlDemo.Information.PnpObjectInfo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Information"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://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>

Information/PnpObjectInfo.xaml.cs

/*
 * 演示如何獲取即插即用(PnP: Plug and Play)的設備的相關信息
 */
    
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" };
            // 通過 PnpObject.FindAllAsync() 獲取所有 PnP 設備的指定的信息(更多的屬性名稱請參見:http://technet.microsoft.com/zh-cn/library/hh464997.aspx)
            var containers = await PnpObject.FindAllAsync(PnpObjectType.DeviceContainer, properties);
    
            // 顯示獲取到的 PnP 設備的相關信息
            foreach (PnpObject container in containers)
            {
                listBox.Items.Add(new DisplayItem(container));
            }
        }

    
        /// <summary>
        /// 用於保存 PnP 設備的相關信息
        /// </summary>
        class DisplayItem
        {
            public string Id { get; private set; }
            public string Name { get; private set; }
            public string Properties { get; private set; }
    
            public DisplayItem(PnpObject container)
            {
                // 該 PnpObject 的名稱
                Name = (string)container.Properties["System.ItemNameDisplay"];
                if (string.IsNullOrWhiteSpace(Name))
                    Name = "未知";
    
                // 該 PnpObject 的標識
                Id = "Id: " + container.Id;
    
                // 該 PnpObject 的信息
                foreach (var property in container.Properties)
                {
                    Properties += property.Key + " = " + property.Value + "\n";
                }
            }
        }
    }
}

5、演示如何獲取常用設備的相關信息

Information/DeviceInfo.xaml

<Page
    x:Class="XamlDemo.Information.DeviceInfo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Information"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://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>

Information/DeviceInfo.xaml.cs

/*
 * 演示如何獲取常用設備的相關信息
 */
    
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();
    
            // {0ECEF634-6EF0-472A-8085-5AD023ECBCCD} - 打印設備
            // {E5323777-F976-4F5B-9B55-B94699C46E44} - 攝像設備
            // {6AC27878-A6FA-4155-BA85-F98F491D4F33} - 便攜設備
    
            // 通過 DeviceInformation.FindAllAsync() - 獲取指定類型的設備信息
            var interfaces = await DeviceInformation.FindAllAsync("System.Devices.InterfaceClassGuid:=\"{6AC27878-A6FA-4155-BA85-F98F491D4F33}\"", null); // 獲取全部便攜設備的設備信息
            // var interfaces = await DeviceInformation.FindAllAsync(DeviceClass.AudioRender); 

// 通過 DeviceClass 枚舉獲取指定類型的設備信息
    
            // 顯示獲取到的常用設備的相關信息
            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 deviceWatcher = DeviceInformation.CreateWatcher();
            // DeviceWatcher 的相關事件有:Added, EnumerationCompleted, Removed, Stopped, Updated
            // DeviceWatcher 的相關方法有:Start(), Stop()
            // DeviceWatcher 的相屬性件有:Status(一個 DeviceWatcherStatus 類型的枚舉)
        }
    
    
        /// <summary>
        /// 用於保存常用設備的相關信息
        /// </summary>
        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);
            }
        }
    }
}

OK

[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved