重新想象 Windows 8 Store Apps (70) - 其它: 文件壓縮和解壓縮, 與 Windows 商店相關的操作, app 與 web, 幾個 Core 的應用, 頁面的生命周期和程序的生命周期


[源碼下載]


重新想象 Windows 8 Store Apps (70) - 其它: 文件壓縮和解壓縮, 與 Windows 商店相關的操作, app 與 web, 幾個 Core 的應用, 頁面的生命周期和程序的生命周期



作者:webabcd


介紹
重新想象 Windows 8 Store Apps 之 其它

  • 文件壓縮和解壓縮
  • 與 Windows 商店相關的操作
  • app 與 web
  • 幾個 Core 的應用
  • 頁面的生命周期和程序的生命周期



示例
1、演示如何壓縮和解壓縮文件
Feature/Compression.xaml

<Page
    x:Class="XamlDemo.Feature.Compression"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Feature"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">
            
            <TextBlock Name="lblMsg" FontSize="14.667" />

            <Button Name="btnXpress" Content="Xpress" Margin="0 10 0 0" Click="btnXpress_Click" />

            <Button Name="btnXpressHuff" Content="XpressHuff" Margin="0 10 0 0" Click="btnXpressHuff_Click" />

            <Button Name="btnMszip" Content="Mszip" Margin="0 10 0 0" Click="btnMszip_Click" />

            <Button Name="btnLzms" Content="Lzms" Margin="0 10 0 0" Click="btnLzms_Click" />
            
        </StackPanel>
    </Grid>
</Page>

Feature/Compression.xaml.cs

/*
 * 演示如何壓縮和解壓縮文件
 * 
 * 注:對於非常小的數據壓縮后可能比壓縮前還要大,已經經過壓縮算法的文件如 jpg mp3 mp4 等再壓縮效果不明顯也可能比之前還大
 */

using System;
using Windows.Storage;
using Windows.Storage.Compression;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XamlDemo.Common;

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

        private void btnXpress_Click(object sender, RoutedEventArgs e)
        {
            // XPRESS 算法
            CompressionDemo(CompressAlgorithm.Xpress);
        }

        private void btnXpressHuff_Click(object sender, RoutedEventArgs e)
        {
            // 具有霍夫曼編碼的 XPRESS 算法
            CompressionDemo(CompressAlgorithm.XpressHuff);
        }

        private void btnMszip_Click(object sender, RoutedEventArgs e)
        {
            // Mszip 算法
            CompressionDemo(CompressAlgorithm.Mszip);
        }

        private void btnLzms_Click(object sender, RoutedEventArgs e)
        {
            // Lzms 算法
            CompressionDemo(CompressAlgorithm.Lzms);
        }

        private async void CompressionDemo(CompressAlgorithm algorithm)
        {
            try
            {
                if (!Helper.EnsureUnsnapped())
                    return;

                // 選擇一個准備壓縮的文件
                var picker = new FileOpenPicker();
                picker.FileTypeFilter.Add("*");
                var originalFile = await picker.PickSingleFileAsync();
                if (originalFile == null)
                    return;

                lblMsg.Text = "選中了文件:" + originalFile.Name;
                lblMsg.Text += Environment.NewLine;



                var compressedFilename = originalFile.Name + ".compressed"; // 注意:為了有讀寫 .compressed 文件的權限,需要在 Package.appxmanifest 中新增一個“文件類型關聯”聲明,並做相關配置
                var compressedFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(compressedFilename, CreationCollisionOption.GenerateUniqueName);
                lblMsg.Text += "創建了一個新文件,用於保存壓縮后的文件:" + compressedFile.Name;
                lblMsg.Text += Environment.NewLine;

                using (var originalInput = await originalFile.OpenReadAsync()) // 打開原始文件
                using (var compressedOutput = await compressedFile.OpenAsync(FileAccessMode.ReadWrite)) // 打開壓縮后的數據的目標文件(目前是一個空文件)
                using (var compressor = new Compressor(compressedOutput.GetOutputStreamAt(0), algorithm, 0)) // 實例化 Compressor
                {
                    var bytesCompressed = await RandomAccessStream.CopyAsync(originalInput, compressor); // 將原始數據寫入到壓縮后的數據的目標文件
                    lblMsg.Text += "已將原始文件的數據寫入到:" + compressedFile.Name;
                    lblMsg.Text += Environment.NewLine;

                    var finished = await compressor.FinishAsync(); // 壓縮指定文件中的數據
                    lblMsg.Text += "此文件中的數據已被壓縮:" + compressedFile.Name; 
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += "壓縮前大小:" + bytesCompressed.ToString() + " - 壓縮后大小:" + compressedOutput.Size.ToString();
                    lblMsg.Text += Environment.NewLine;
                }



                var decompressedFilename = originalFile.Name + ".decompressed"; // 注意:為了有讀寫 .decompressed 文件的權限,需要在 Package.appxmanifest 中新增一個“文件類型關聯”聲明,並做相關配置
                var decompressedFile = await KnownFolders.DocumentsLibrary.CreateFileAsync(decompressedFilename, CreationCollisionOption.GenerateUniqueName);
                lblMsg.Text += "創建了一個新文件,用於保存解壓縮后的文件:" + decompressedFile.Name;
                lblMsg.Text += Environment.NewLine;

                using (var compressedInput = await compressedFile.OpenSequentialReadAsync()) // 打開經過壓縮的文件
                using (var decompressedOutput = await decompressedFile.OpenAsync(FileAccessMode.ReadWrite)) // 打開解壓縮后的數據的目標文件(目前是一個空文件)
                using (var decompressor = new Decompressor(compressedInput)) // 實例化 Compressor
                {
                    var bytesDecompressed = await RandomAccessStream.CopyAsync(decompressor, decompressedOutput); // 解壓縮數據,並將解壓縮后的數據保存到目標文件
                    lblMsg.Text += "文件解壓縮完成:" + decompressedFile.Name;
                    lblMsg.Text += Environment.NewLine;
                    lblMsg.Text += "解壓縮后的大小:" + bytesDecompressed.ToString();
                    lblMsg.Text += Environment.NewLine;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.ToString();
            }
        }
    }
}


2、演示與 Windows 商店相關的操作
Feature/StoreDemo.xaml

<Page
    x:Class="XamlDemo.Feature.StoreDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Feature"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <Button Name="btnOpenAppInStore" Content="跳轉到 Windows 商店中指定 app 的主頁" Click="btnOpenAppInStore_Click" />

            <Button Name="btnReviewAppInStore" Content="在 Windows 商店中評論指定的 app" Click="btnReviewAppInStore_Click" Margin="0 10 0 0" />

            <Button Name="btnSearchAppInStore" Content="在 Windows 商店中通過關鍵字搜索 app" Click="btnSearchAppInStore_Click" Margin="0 10 0 0" />

            <Button Name="btnUpdateAppInStore" Content="跳轉到 Windows 商店中的 app 更新頁" Click="btnUpdateAppInStore_Click" Margin="0 10 0 0" />


            <TextBlock Name="lblMsg" FontSize="14.667" Text="與購買相關的部分,請參見 code-behind 中的代碼" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

Feature/StoreDemo.xaml.cs

/*
 * 演示與 Windows 商店相關的操作
 * 
 * 注:
 * 測試時可以使用 CurrentAppSimulator 來模擬購買行為,msdn 上有對應的 sample 可以下載 
 */

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

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

        private async void btnOpenAppInStore_Click(object sender, RoutedEventArgs e)
        {
            // 跳轉到 Windows 商店中指定 app 的主頁(PDP - program display page; PFN - package family name)
            await Launcher.LaunchUriAsync(new Uri(@"ms-windows-store:PDP?PFN=10437webabcd.173815756DD78_s2b9shdpk31kj"));
        }

        private async void btnReviewAppInStore_Click(object sender, RoutedEventArgs e)
        {
            // 在 Windows 商店中評論指定的 app(PFN - package family name)
            await Launcher.LaunchUriAsync(new Uri(@"ms-windows-store:REVIEW?PFN=10437webabcd.173815756DD78_s2b9shdpk31kj"));
        }

        private async void btnSearchAppInStore_Click(object sender, RoutedEventArgs e)
        {
            // 在 Windows 商店中通過關鍵字搜索 app
            await Launcher.LaunchUriAsync(new Uri(@"ms-windows-store:Search?query=貪吃蛇"));
        }

        private async void btnUpdateAppInStore_Click(object sender, RoutedEventArgs e)
        {
            // 跳轉到 Windows 商店中的 app 更新頁
            await Launcher.LaunchUriAsync(new Uri(@"ms-windows-store:Updates"));
        }



        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            CurrentAppDemo();

            LicenseInformationDemo();
        }

        private void CurrentAppDemo()
        {
            // 由 Windows 商店創建的此 app 的 id
            // CurrentApp.AppId;

            // 獲取此 app 在 Windows 商店中的 URI 地址
            // CurrentApp.LinkUri;

            // 獲取當前 app 的 LicenseInformation 對象
            // CurrentApp.LicenseInformation;

            // 請求應用程序內購買完整許可證
            // CurrentApp.RequestAppPurchaseAsync();

            // 請求應用程序內購買指定產品的許可證
            // CurrentApp.RequestProductPurchaseAsync

            // 獲取此 app 的全部購買記錄
            // CurrentApp.GetAppReceiptAsync();

            // 獲取此 app 的指定產品的購買記錄
            // CurrentApp.GetProductReceiptAsync();

            // 獲取此 app 的 ListingInformation 信息
            // CurrentApp.LoadListingInformationAsync();


            // ListingInformation - 此 app 在 Windows 商店中的相關信息
            //     AgeRating - app 的年齡分級            
            //     CurrentMarket - app 的當前商店,如:en-us
            //     Name - app 在當前商店中的名稱
            //     FormattedPrice - app 在當前商店中的價格
            //     Description - app 在當前商店中的程序說明
            //     ProductListings - app 在當前商店中的 ProductListing 集合


            // ProductListing - app 的產品信息
            //     ProductId - 產品 ID
            //     Name - 產品名稱
            //     FormattedPrice - 產品當前市場的格式化后的價格
        }

        private void LicenseInformationDemo()
        {
            // 當前 app 的許可證信息
            LicenseInformation licenseInformation = CurrentApp.LicenseInformation;

            // 許可證ok則為true,否則無許可證或許可證過期則為false
            // licenseInformation.IsActive;  

            // 是否是試用許可證
            // licenseInformation.IsTrial;

            // 許可證的到期時間
            // licenseInformation.ExpirationDate;

            // 許可證狀態發生變化時所觸發的事件
            // licenseInformation.LicenseChanged;

            // 獲取此 app 相關的 ProductLicenses 集合
            // licenseInformation.ProductLicenses;


            // ProductLicense - 產品許可證
            //     ProductId - 產品 ID
            //     IsActive - 此產品許可證ok則為true,否則無此產品許可證或此產品許可證過期則為false
            //     ExpirationDate - 此產品許可證的到期時間
        }
    }
}


3、演示與 Windows 商店相關的操作
WebServer/AppAndWeb.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <!--
        以下簡介如何將網站連接到 Windows 應用商店應用    
        關於 app 與 web 的更多內容請參見:http://msdn.microsoft.com/zh-cn/library/ie/hh781489(v=vs.85).aspx
    -->

    <!--包名稱,系統會通過此值在本地查找應用,如果有則右下角的按鈕會顯示“切換到 xxx 應用”,選中后會啟動對應的應用-->
    <meta name="msApplication-ID" content="microsoft.microsoftskydrive" />

    <!--包系列名稱,當無法通過包名稱查找到本地應用時,右下角的按鈕會顯示“獲取此網站的應用”,選中后會通過包系列名稱在 Windows 商店中查找-->
    <meta name="msApplication-PackageFamilyName" content="microsoft.microsoftskydrive_8wekyb3d8bbwe" />

    <!--
        啟動對應的應用時,傳遞過去的參數

        app 中通過如下方法獲取參數
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!String.IsNullOrEmpty(args.Arguments)) 
            {
            
            }
        }
    -->
    <meta name="msApplication-Arguments" content="hello webabcd" />

    <title>app and web</title>
</head>
<body>
    metro ie 打開,可以通過右下角的按鈕“獲取此網站的應用”或“切換到 xxx 應用”
</body>
</html>


4、演示幾個 Core 的應用
Feature/CoreDemo.xaml.cs

/*
 * 演示幾個 Core 的應用
 */

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

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

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            CoreDispatcherDemo();

            CoreWindowDemo();

            CoreApplicationDemo();
        }

        private async void CoreDispatcherDemo()
        {
            // CoreDispatcher - 消息調度器
            Windows.UI.Core.CoreDispatcher coreDispatcher = Windows.UI.Xaml.Window.Current.Dispatcher;

            await coreDispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
            {
                // 調用 coreDispatcher 所在的線程
            });

            coreDispatcher.AcceleratorKeyActivated += (Windows.UI.Core.CoreDispatcher sender, Windows.UI.Core.AcceleratorKeyEventArgs args) =>
            {
                // 當快捷鍵被激活(按住)時所觸發的事件
            };
        }

        private void CoreWindowDemo()
        {
            // CoreWindow - 窗口對象,可以監測用戶的輸入
            Windows.UI.Core.CoreWindow coreWindow = Windows.UI.Xaml.Window.Current.CoreWindow;

            // coreWindow.KeyDown - 按鍵按下時觸發的事件
            // coreWindow.PointerPressed - 指針按下時觸發的事件
            // coreWindow.GetAsyncKeyState(VirtualKey virtualKey) - 異步返回虛擬鍵的狀態
            // coreWindow.GetKeyState(VirtualKey virtualKey) - 返回虛擬鍵的狀態
            // coreWindow.Activate(), coreWindow.Close() - 激活窗口, 關閉窗口
            // coreWindow.Activated, coreWindow.Closed - 窗口被激活時觸發的事件,窗口被關閉時觸發的事件
            // coreWindow.Dispatcher - 窗口的消息調度器
            // coreWindow.Bounds - 窗口的邊框
        }

        private void CoreApplicationDemo()
        {
            // Windows.ApplicationModel.Core.CoreApplication.Id - 獲取 Package.appxmanifest 中 <Application Id="Win8App" /> 所配置的值

            // Windows.ApplicationModel.Core.CoreApplication.Exiting - 關閉應用程序時觸發的事件
            // Windows.ApplicationModel.Core.CoreApplication.Resuming - 繼續應用程序時觸發的事件
            // Windows.ApplicationModel.Core.CoreApplication.Suspending - 掛起應用程序時觸發的事件

            // Windows.ApplicationModel.Core.CoreApplication.Properties - 一個字典表,用於在應用程序運行時保存和獲取全局信息
        }
    }
}


5、簡述頁面的生命周期和程序的生命周期
Feature/LifeCycle.xaml.cs

/*
 * 頁面生命周期:
 * 1、導航相關的就是:OnNavigatedTo(), OnNavigatingFrom(), OnNavigatedFrom()
 * 2、關於導航的更多內容參見:Controls/Frame/Demo.xaml
 * 3、有一點需要注意:Popup 中的內容每次顯示時都會觸發 Loaded 事件
 * 
 * 
 * 程序生命周期(參見:App.xaml.cs):
 * 1、OnSuspending() 時保存狀態
 * 2、OnLaunched() 時恢復狀態
 * 3、Suspending - 轉為掛起狀態時觸發的事件
 * 4、Resuming - 由掛起狀態轉為運行狀態時觸發的事件
 */

using Windows.UI.Xaml.Controls;

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



OK
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM