背水一戰 Windows 10 (100) - 應用間通訊: 分享

[源碼下載]


html

背水一戰 Windows 10 (100) - 應用間通訊: 分享



做者:webabcd


介紹
背水一戰 Windows 10 之 應用間通訊html5

  • 分享



示例
一、本例用於演示如何開發一個分享的分享源
App2AppCommunication/ShareSource.xamlc++

<Page
    x:Class="Windows10.App2AppCommunication.ShareSource"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows10.App2AppCommunication"
    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="10 0 10 10">

            <TextBlock Name="lblMsg" Margin="5" />

            <Button Content="Share Text" Click="Button_Click" Margin="5" />

            <Button Content="Share Web Link" Click="Button_Click" Margin="5" />

            <Button Content="Share Application Link" Click="Button_Click" Margin="5" />

            <Button Content="Share Image" Click="Button_Click" Margin="5" />

            <Button Content="Share File" Click="Button_Click" Margin="5" />

            <Button Content="Share Html" Click="Button_Click" Margin="5" />

            <Button Content="Share Custom Protocol" Click="Button_Click" Margin="5" />

            <Button Content="Share With Deferral" Click="Button_Click" Margin="5" />

            <Button Content="Share Failed" Click="Button_Click" Margin="5" />

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

App2AppCommunication/ShareSource.xaml.csweb

/*
 * 本例用於演示如何開發一個分享的分享源(分享目標的示例參見 /MyShareTarget/MainPage.xaml.cs)
 *
 * 分享源 - 提供分享數據的 app
 * 分享目標 - 接收並處理分享數據的 app
 * 分享面板 - 點擊「分享」後出來的,包含了一堆分享目標的面板
 *
 *
 * DataTransferManager - 分享數據管理器
 *     GetForCurrentView() - 返回當前窗口關聯的 DataTransferManager 對象
 *     ShowShareUI() -  彈出分享面板,以開始分享操做
 *     DataRequested - 分享操做開始時(即彈出分享面板後)所觸發的事件,事件參數爲 DataTransferManager 和 DataRequestedEventArgs
 *     TargetApplicationChosen - 選中了分享面板上的某個分享目標時所觸發的事件,事件參數爲 DataTransferManager 和 TargetApplicationChosenEventArgs
 * 
 * TargetApplicationChosenEventArgs - TargetApplicationChosen 的事件參數
 *     ApplicationName - 選中的分享目標的名稱
 *     
 * DataRequestedEventArgs - DataRequested 的事件參數
 *     Request - 返回 DataRequest 類型的數據
 *     
 * DataRequest - 一個對象,其包括了分享的內容和錯誤提示
 *     FailWithDisplayText() - 當須要分享的數據不合法時,須要在分享面板上顯示的提示信息
 *     Data - 須要分享的內容,返回 DataPackage 對象
 *         
 * DataPackage - 分享內容(注:複製到剪切板的內容也是經過此對象來封裝)
 *     Properties - 返回 DataPackagePropertySetView 對象
 *         Properties.Title - 分享數據的標題
 *         Properties.Description - 分享數據的描述
 *         Properties.Thumbnail - 分享數據的縮略圖
 *         ApplicationName - 分享源的 app 的名稱
 *         PackageFamilyName - 分享源的 app 的包名
 *         ApplicationListingUri - 分享源的 app 在商店中的地址
 *         ContentSourceApplicationLink - 內容源的 ApplicationLink
 *         ContentSourceWebLink - 內容源的 WebLink
 *         Square30x30Logo - 分享源的 app 的 30 x 30 的 logo
 *         LogoBackgroundColor - 分享源的 app 的 logo 的背景色
 *         FileTypes - 獲取分享數據中包含的文件類型
 *     SetText(), SetWebLink(), SetApplicationLink(), SetHtmlFormat(), SetBitmap(), SetStorageItems(), SetData(), SetDataProvider() - 設置須要分享的各類格式的數據,詳細用法見下面的相關 demo(注:一個 DataPackage 能夠有多種不一樣格式的數據)
 *     ResourceMap - IDictionary<string, RandomAccessStreamReference> 類型,分享 html 時若是其中包含了本地資源的引用(如引用了本地圖片),則須要經過 ResourceMap 傳遞
 *     GetView() - 返回 DataPackageView 對象,其至關於 DataPackage 的一個只讀副本,詳細說明見 /MyShareTarget/MainPage.xaml.cs
 *     
 *     
 * 異步分享:
 * 一、DataPackage 經過 SetDataProvider() 傳遞數據,其對應的委託的參數爲一個 DataProviderRequest 類型的數據
 * 二、DataProviderRequest.GetDeferral() 用於獲取 DataProviderDeferral 對象以開始異步處理,而後經過 DataProviderDeferral.Complete() 完成異步操做
 * 
 * 
 * 注:
 * 一個 DataPackage 能夠包含多種不一樣格式的數據(本例爲了演示的清晰,每次只會分享一種格式的數據)
 */

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using System.Linq;
using Windows.Graphics.Imaging;
using Windows.UI;

namespace Windows10.App2AppCommunication
{
    public sealed partial class ShareSource : Page
    {
        // 當前須要分享的內容的類型
        private string _shareType = "Share Text";
        // 須要分享的文件集合
        private IReadOnlyList<StorageFile> _selectedFiles;


        public ShareSource()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 初始化 DataTransferManager
            DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += dataTransferManager_DataRequested;
            dataTransferManager.TargetApplicationChosen += dataTransferManager_TargetApplicationChosen;
        }

        // 分享操做開始時(即彈出分享面板後)
        void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            // 根據須要分享的內容的類型執行指定的方法
            switch (_shareType)
            {
                case "Share Text":
                    ShareText(sender, args);
                    break;
                case "Share Web Link":
                    ShareWebLink(sender, args);
                    break;
                case "Share Application Link":
                    ShareApplicationLink(sender, args);
                    break;
                case "Share Image":
                    ShareImage(sender, args);
                    break;
                case "Share File":
                    ShareFile(sender, args);
                    break;
                case "Share With Deferral":
                    ShareWithDeferral(sender, args);
                    break;
                case "Share Html":
                    ShareHtml(sender, args);
                    break;
                case "Share Custom Protocol":
                    ShareCustomProtocol(sender, args);
                    break;
                case "Share Failed":
                    ShareFailed(sender, args);
                    break;
                default:
                    break;
            }
        }

        // 選中了分享面板上的某個分享目標時
        void dataTransferManager_TargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs args)
        {
            // 顯示用戶須要與其分享內容的應用程序的名稱
            lblMsg.Text = "分享給:" + args.ApplicationName;
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            _shareType = (sender as Button).Content.ToString();

            // 若是須要分享文件,則提示用戶選擇文件
            if (_shareType == "Share Image" || _shareType == "Share File" || _shareType == "Share With Deferral")
            {
                FileOpenPicker filePicker = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.List,
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                    FileTypeFilter = { "*" }
                    // FileTypeFilter = { ".jpg", ".png", ".bmp", ".gif", ".tif" }
                };

                _selectedFiles = await filePicker.PickMultipleFilesAsync();
                if (_selectedFiles.Count > 0)
                {
                    // 彈出分享面板,以開始分享操做
                    DataTransferManager.ShowShareUI();
                }
            }
            else
            {
                // 彈出分享面板,以開始分享操做
                DataTransferManager.ShowShareUI();
            }
        }

        // 分享文本的 Demo
        private void ShareText(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);
            dataPackage.SetText("須要分享的詳細內容");
        }

        // 分享 WebLink 的 Demo
        private void ShareWebLink(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);
            dataPackage.SetWebLink(new Uri("http://webabcd.cnblogs.com"));
        }

        // 分享 ApplicationLink 的 Demo
        private void ShareApplicationLink(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);
            dataPackage.SetApplicationLink(new Uri("webabcd:data"));
        }

        // 分享圖片的 Demo(關於如何爲分享的圖片減肥請參見本例的「異步分享的 Demo」)
        private void ShareImage(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);

            // 分享選中的全部文件中的第一個文件(假設其是圖片)
            RandomAccessStreamReference imageStreamRef = RandomAccessStreamReference.CreateFromFile(_selectedFiles.First());
            dataPackage.Properties.Thumbnail = imageStreamRef;
            dataPackage.SetBitmap(imageStreamRef);
        }

        // 分享文件的 Demo
        private void ShareFile(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);
            dataPackage.SetStorageItems(_selectedFiles);
        }

        // 分享 html 的 Demo
        private void ShareHtml(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            string localImage = "ms-appx:///Assets/StoreLogo.png";
            string htmlExample = "<p><b>webabcd</b><img src=\"" + localImage + "\" /></p>";
            // 爲 html 添加分享所需的必要的標頭,以保證能夠正常進行 html 的分享操做
            string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlExample);

            DataPackage dataPackage = GetDataPackage(args);
            dataPackage.SetHtmlFormat(htmlFormat);

            // 設置本地圖像數據(若是須要分享的 html 包含本地圖像,則只能經過這種方法分享之)
            RandomAccessStreamReference streamRef = RandomAccessStreamReference.CreateFromUri(new Uri(localImage));
            dataPackage.ResourceMap[localImage] = streamRef;

            /*
             * 如下演示如何分享 WebView 中的被用戶選中的 html
             * 具體可參見:Controls/WebViewDemo/WebViewDemo6.xaml
             * 
            DataPackage dataPackage = WebView.DataTransferPackage;
            DataPackageView dataPackageView = dataPackage.GetView();

            if ((dataPackageView != null) && (dataPackageView.AvailableFormats.Count > 0))
            {
                dataPackage.Properties.Title = "Title";
                dataPackage.Properties.Description = "Description";
            
                args.Request.Data = dataPackage;
            }
            */
        }

        // 分享自定義協議的 Demo
        private void ShareCustomProtocol(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);

            // 指定須要分享的自定義協議和自定義數據,第一個參數是自定義數據的格式 id,也就是自定義協議(要使用標準格式 id 的話,就是 Windows.ApplicationModel.DataTransfer.StandardDataFormats 枚舉)
            // 須要在 SourceTarget 的 Package.appxmanifest 中的「共享目標」聲明中對自定義格式 id 作相應的配置
            dataPackage.SetData("http://webabcd/sharedemo", "自定義數據");
        }

        // 異步分享的 Demo(在分享內容須要較長時間才能計算出來的場景下,應該使用異步分享)
        private void ShareWithDeferral(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            DataPackage dataPackage = GetDataPackage(args);

            dataPackage.Properties.Thumbnail = RandomAccessStreamReference.CreateFromFile(_selectedFiles.First());
            // 經過委託來提供分享數據,當用戶點擊了分享目標後會調用此委託,即不立刻提供分享數據,而是等到用戶點擊了分享目標後再異步準備數據
            dataPackage.SetDataProvider(StandardDataFormats.Bitmap, providerRequest => this.OnDeferredImageRequestedHandler(providerRequest, _selectedFiles.First()));
        }

        // 用戶點擊了分享目標後會調用此方法
        private async void OnDeferredImageRequestedHandler(DataProviderRequest providerRequest, StorageFile imageFile)
        {
            // 獲取 DataProviderDeferral,以開始異步處理
            DataProviderDeferral deferral = providerRequest.GetDeferral();
            InMemoryRandomAccessStream inMemoryStream = new InMemoryRandomAccessStream();

            try
            {
                // 將用戶選中的圖片縮小一倍,而後再分享
                IRandomAccessStream imageStream = await imageFile.OpenAsync(FileAccessMode.Read);
                BitmapDecoder imageDecoder = await BitmapDecoder.CreateAsync(imageStream);
                BitmapEncoder imageEncoder = await BitmapEncoder.CreateForTranscodingAsync(inMemoryStream, imageDecoder);
                imageEncoder.BitmapTransform.ScaledWidth = (uint)(imageDecoder.OrientedPixelWidth * 0.5);
                imageEncoder.BitmapTransform.ScaledHeight = (uint)(imageDecoder.OrientedPixelHeight * 0.5);
                await imageEncoder.FlushAsync();

                // 停 3 秒,以模擬長時間任務
                await Task.Delay(3000);

                providerRequest.SetData(RandomAccessStreamReference.CreateFromStream(inMemoryStream));
            }
            finally
            {
                // 完成異步操做
                deferral.Complete();
            }
        }

        // 須要分享的數據不合法時如何處理的 Demo
        private void ShareFailed(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            // 判斷須要分享的數據是否合法,不合法的話就調用下面的方法,用以在分享面板上顯示指定的提示信息
            if (true)
            {
                args.Request.FailWithDisplayText("須要分享的數據不合法,分享操做失敗");
            }
        }



        // 用於設置分享的數據
        private DataPackage GetDataPackage(DataRequestedEventArgs args)
        {
            DataPackage dataPackage = args.Request.Data;

            dataPackage.Properties.Title = "Title";
            dataPackage.Properties.Description = "Description";
            dataPackage.Properties.ContentSourceApplicationLink = new Uri("webabcd:data");
            dataPackage.Properties.ContentSourceWebLink = new Uri("http://webabcd.cnblogs.com/");

            // 下面這些數據不指定的話,系統會自動爲其設置好相應的值
            dataPackage.Properties.ApplicationListingUri = new Uri("https://www.microsoft.com/store/apps/9pd68q7017mw");
            dataPackage.Properties.ApplicationName = "ApplicationName";
            dataPackage.Properties.PackageFamilyName = "PackageFamilyName";
            dataPackage.Properties.Square30x30Logo = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/StoreLogo.png"));
            dataPackage.Properties.LogoBackgroundColor = Colors.Red;

            return dataPackage;
        }
    }
}


二、本例用於演示如何開發一個分享的分享目標
App.xaml.csexpress

        // 經過「分享」激活應用程序時所調用的方法
        protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
        {
            var rootFrame = new Frame();
            rootFrame.Navigate(typeof(MainPage), args);
            Window.Current.Content = rootFrame;

            Window.Current.Activate();
        }

MyShareTarget/MainPage.xamlwindows

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

    <Grid Background="{ThemeResource SystemAccentColor}">

        <ScrollViewer Name="scrollView" Margin="10 0 10 10">
            <StackPanel>
                <TextBlock Name="lblMsg" Margin="5" />

                <StackPanel Margin="5">
                    <TextBlock Text="Square30x30Logo: " />
                    <Image Name="imgLogo" HorizontalAlignment="Left" Width="100" Height="100" />
                </StackPanel>

                <StackPanel Margin="5">
                    <TextBlock Text="分享圖片的縮略圖: " />
                    <Image Name="imgThumbnail" HorizontalAlignment="Left" Width="300" />
                </StackPanel>

                <StackPanel Margin="5">
                    <TextBlock Text="分享圖片的原圖: " />
                    <Image Name="imgBitmap" HorizontalAlignment="Left" Width="300" />
                </StackPanel>
            </StackPanel>
        </ScrollViewer>

    </Grid>
</Page>

MyShareTarget/MainPage.xaml.csapp

/*
 * 本例用於演示如何開發一個分享的分享目標(分享源的示例參見 /Windows10/App2AppCommunication/ShareSource.xaml.cs)
 * 一、在 Package.appxmanifest 中新增一個「共享目標」聲明,並作相關配置(支持的文件類型,支持的分享數據的格式),相似以下
 * <Extensions>
 *   <uap:Extension Category="windows.shareTarget">
 *     <uap:ShareTarget>
 *       <uap:SupportedFileTypes>
 *         <uap:SupportsAnyFileType />
 *       </uap:SupportedFileTypes>
 *       <uap:DataFormat>Text</uap:DataFormat>
 *       <uap:DataFormat>WebLink</uap:DataFormat>
 *       <uap:DataFormat>ApplicationLink</uap:DataFormat>
 *       <uap:DataFormat>Html</uap:DataFormat>
 *       <uap:DataFormat>Bitmap</uap:DataFormat>
 *       <uap:DataFormat>http://webabcd/sharedemo</uap:DataFormat>
 *     </uap:ShareTarget>
 *   </uap:Extension>
 * </Extensions>
 * 二、在 App.xaml.cs 中 override void OnShareTargetActivated(ShareTargetActivatedEventArgs args),以獲取相關的分享信息
 * 
 * 
 * ShareTargetActivatedEventArgs - 當 app 由分享激活時的事件參數
 *     ShareOperation - 返回一個 ShareOperation 類型的對象
 *     PreviousExecutionState - 此 app 被分享激活前的執行狀態(ApplicationExecutionState 枚舉:NotRunning, Running, Suspended, Terminated, ClosedByUser)
 *     SplashScreen - 啓動畫面對象
 * 
 * ShareOperation - 分享操做的相關信息
 *     Data - 返回 DataPackageView 對象,其至關於 DataPackage 的一個只讀副本
 *     ReportCompleted(), ReportStarted(), ReportDataRetrieved(), ReportError(), ReportSubmittedBackgroundTask() - 顧名思義的一些方法,用不用皆可,它們的做用是能夠幫助系統優化資源的使用
 * 
 * DataPackageView - DataPackage 對象的只讀版本,從剪切板獲取數據或者分享目標接收數據均經過此對象來獲取 DataPackage 對象的數據
 *     AvailableFormats - DataPackage 中數據所包含的全部格式
 *     Contains() - 是否包含指定格式的數據
 *     Properties - 返回 DataPackagePropertySetView 對象,就是由分享源所設置的一些信息
 *     Properties.Title - 分享數據的標題
 *         Properties.Description - 分享數據的描述
 *         Properties.Thumbnail - 分享數據的縮略圖
 *         ApplicationName - 分享源的 app 的名稱
 *         PackageFamilyName - 分享源的 app 的包名
 *         ApplicationListingUri - 分享源的 app 在商店中的地址
 *         ContentSourceApplicationLink - 內容源的 ApplicationLink
 *         ContentSourceWebLink - 內容源的 WebLink
 *         Square30x30Logo - 分享源的 app 的 30 x 30 的 logo
 *         LogoBackgroundColor - 分享源的 app 的 logo 的背景色
 *         FileTypes - 獲取分享數據中包含的文件類型
 *     GetTextAsync(), GetWebLinkAsync(), GetApplicationLinkAsync(), GetHtmlFormatAsync(), GetBitmapAsync(), GetStorageItemsAsync(), GetDataAsync(), GetResourceMapAsync() - 獲取分享過來的各類格式的數據,詳細用法見下面的相關 demo(注:一個 DataPackage 能夠有多種不一樣格式的數據)
 */

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.DataTransfer.ShareTarget;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

namespace MyShareTarget
{
    public sealed partial class MainPage : Page
    {
        private ShareOperation _shareOperation;

        public MainPage()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 獲取分享激活 app 時的事件參數 ShareTargetActivatedEventArgs,可在 App.xaml.cs 的 override void OnShareTargetActivated(ShareTargetActivatedEventArgs args) 中拿到
            ShareTargetActivatedEventArgs shareTargetActivated = e.Parameter as ShareTargetActivatedEventArgs;
            if (shareTargetActivated == null)
            {
                lblMsg.Text = "爲了演示分享目標,請從分享源激活本程序";
                return;
            }
            // 獲取分享的 ShareOperation 對象
            _shareOperation = shareTargetActivated.ShareOperation;

            // 異步獲取分享數據
            await Task.Factory.StartNew(async () =>
            {
                // 顯示分享數據的相關信息
                OutputMessage("Title: " + _shareOperation.Data.Properties.Title);
                OutputMessage("Description: " + _shareOperation.Data.Properties.Description);
                OutputMessage("ApplicationName: " + _shareOperation.Data.Properties.ApplicationName);
                OutputMessage("PackageFamilyName: " + _shareOperation.Data.Properties.PackageFamilyName);
                OutputMessage("ApplicationListingUri: " + _shareOperation.Data.Properties.ApplicationListingUri);
                OutputMessage("ContentSourceApplicationLink: " + _shareOperation.Data.Properties.ContentSourceApplicationLink);
                OutputMessage("ContentSourceWebLink: " + _shareOperation.Data.Properties.ContentSourceWebLink);
                OutputMessage("LogoBackgroundColor: " + _shareOperation.Data.Properties.LogoBackgroundColor);
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    IRandomAccessStreamWithContentType logoStream = await _shareOperation.Data.Properties.Square30x30Logo.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(logoStream);
                    imgLogo.Source = bitmapImage;
                });
                OutputMessage("");

                

                // 若是分享數據中包含 Text 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.Text))
                {
                    try
                    {
                        var text = await _shareOperation.Data.GetTextAsync();
                        OutputMessage("Text: " + text);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含 WebLink 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.WebLink))
                {
                    try
                    {
                        var uri = await _shareOperation.Data.GetWebLinkAsync();
                        OutputMessage("WebLink: " + uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含 ApplicationLink 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.ApplicationLink))
                {
                    try
                    {
                        var uri = await _shareOperation.Data.GetApplicationLinkAsync();
                        OutputMessage("ApplicationLink: " + uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含 Bitmap 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.Bitmap))
                {
                    try
                    {
                        IRandomAccessStreamReference stream = await _shareOperation.Data.GetBitmapAsync();
                        ShowBitmap(stream);

                        ShowThumbnail(_shareOperation.Data.Properties.Thumbnail);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含 Html 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.Html))
                {
                    try
                    {
                        // 獲取 html 數據
                        var html = await _shareOperation.Data.GetHtmlFormatAsync();
                        OutputMessage("Html: " + html);

                        // 獲取 html 中包含的本地資源的引用(如引用的本地圖片等),其數據在分享源的 DataPackage.ResourceMap 中設置
                        IReadOnlyDictionary<string, RandomAccessStreamReference> sharedResourceMap = await _shareOperation.Data.GetResourceMapAsync();
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含 StorageItems 格式數據,則顯示之
                if (_shareOperation.Data.Contains(StandardDataFormats.StorageItems))
                {
                    try
                    {
                        var storageItems = await _shareOperation.Data.GetStorageItemsAsync();
                        foreach (var storageItem in storageItems)
                        {
                            OutputMessage("storageItem: " + storageItem.Path);
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 若是分享數據中包含「http://webabcd/sharedemo」格式數據,則顯示之
                if (_shareOperation.Data.Contains("http://webabcd/sharedemo"))
                {
                    try
                    {
                        var customData = await _shareOperation.Data.GetTextAsync("http://webabcd/sharedemo");
                        OutputMessage("Custom Data: " + customData);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }
            });
        }

        // 在 UI 上輸出指定的信息
        async private void OutputMessage(string message)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                lblMsg.Text += message;
                lblMsg.Text += Environment.NewLine;
            });
        }

        // 顯示圖片
        async private void ShowThumbnail(IRandomAccessStreamReference thumbnail)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                if (thumbnail != null)
                {
                    IRandomAccessStreamWithContentType thumbnailStream = await thumbnail.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(thumbnailStream);

                    imgThumbnail.Source = bitmapImage;
                }
            });
        }

        // 顯示圖片
        async private void ShowBitmap(IRandomAccessStreamReference bitmap)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                if (bitmap != null)
                {
                    IRandomAccessStreamWithContentType bitmapStream = await bitmap.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(bitmapStream);

                    imgBitmap.Source = bitmapImage;
                }
            });
        }



        /*
         * 關於 QuickLink 的相關說明以下
         * 注:經測試,在個人 windows 10 環境中,此部份內容無效(應該是 windows 10 已經再也不支持 QuickLink 了)
         * 
         * ShareOperation - 分享操做的相關信息
         *     QuickLinkId - 若是是 QuickLink 激活的,此屬性可獲取此 QuickLink 的 Id
         *     RemoveThisQuickLink() - 若是是 QuickLink 激活的,此方法可刪除此 QuickLink
         *     ReportCompleted(QuickLink quicklink) - 指定一個須要增長的 QuickLink 對象,而後通知系統分享操做已經完成(會自動關閉分享面板)
         *     
         * QuickLink - 預約義了一些數據,指向相應分享目標的一個快捷方式,其會出如今分享面板的上部
         *     Id - 預約義數據
         *     Title - QuickLink 出如今分享面板上的時候所顯示的名稱
         *     Thumbnail - QuickLink 出如今分享面板上的時候所顯示的圖標
         *     SupportedDataFormats - 分享數據中所包含的數據格式與此定義相匹配(有一個匹配便可),QuickLink 纔會出如今分享面板上
         *     SupportedFileTypes - 分享數據中所包含的文件的擴展名與此定義的相匹配(有一個匹配便可),QuickLink 纔會出如今分享面板上
         *     
         * QuickLink 的適用場景舉例
         * 一、當用戶老是分享信息到某一個郵件地址時,即可以在分享目標中以此郵件地址爲 QuickLinkId 生成一個 QuickLink
         * 二、下回用戶再分享時,此 QuickLink 就會出如今分享面板上,用戶在分享面板上能夠點擊此 QuickLink 激活分享目標
         * 三、分享目標被 QuickLink 激活後即可以經過 ShareOperation 對象獲取到 QuickLink,而後就能夠拿到用戶須要分享到的郵件地址(就是 QuickLink 的 Id),從而避免用戶輸入此郵件地址,從而方便用戶的分享操做
         */

        // 演示如何增長一個 QuickLink
        private async void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            OutputMessage("QuickLinkId: " + _shareOperation.QuickLinkId);
            
            QuickLink quickLink = new QuickLink
            {
                Id = "wanglei@email.com",
                Title = "分享到郵件: wanglei@email.com", // QuickLink 在分享面板上顯示的內容

                SupportedFileTypes = { "*" },
                SupportedDataFormats =
                {
                    StandardDataFormats.Text,
                    StandardDataFormats.WebLink,
                    StandardDataFormats.ApplicationLink,
                    StandardDataFormats.Bitmap,
                    StandardDataFormats.StorageItems,
                    StandardDataFormats.Html,
                    "http://webabcd/sharedemo"
                }
            };

            try
            {
                // 設置 QuickLink 在分享面板上顯示的圖標
                StorageFile iconFile = await Package.Current.InstalledLocation.CreateFileAsync("Assets\\StoreLogo.png", CreationCollisionOption.OpenIfExists);
                quickLink.Thumbnail = RandomAccessStreamReference.CreateFromFile(iconFile);

                // 完成分享操做,同時在分享面板上增長一個指定的 QuickLink
                _shareOperation.ReportCompleted(quickLink);
            }
            catch (Exception ex)
            {
                OutputMessage(ex.ToString());
            }
        }
    }
}



OK
[源碼下載]asp.net

相關文章
相關標籤/搜索