重新想象 Windows 8 Store Apps (33) - 關聯啟動: 使用外部程序打開一個文件或uri, 關聯指定的文件類型或協議


[源碼下載]


重新想象 Windows 8 Store Apps (33) - 關聯啟動: 使用外部程序打開一個文件或uri, 關聯指定的文件類型或協議



作者:webabcd


介紹
重新想象 Windows 8 Store Apps 之 關聯啟動

  • 使用外部程序打開一個文件
  • 使用外部程序打開一個 Uri
  • 關聯指定的文件類型(即用本程序打開指定類型的文件)
  • 關聯指定的協議(即用本程序處理指定的協議)



示例
1、演示如何使用外部程序打開一個文件
AssociationLaunching/LaunchFile.xaml

<Page
    x:Class="XamlDemo.AssociationLaunching.LaunchFile"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Launcher"
    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" Margin="0 0 0 10" />

            <RadioButton Content="使用默認打開方式打開文件" Name="radDefault" GroupName="LaunchType" IsChecked="True" />
            <RadioButton Content="使用默認打開方式打開文件,打開前彈出警告框" Name="radWarning" GroupName="LaunchType" />
            <RadioButton Content="選擇指定的打開方式打開文件" Name="radOpenWith" GroupName="LaunchType" />
            
            <Button Content="打開一個 .png 格式文件" Name="btnLaunchFile" Click="btnLaunchFile_Click_1" Margin="0 10 0 0" />
        </StackPanel>
    </Grid>
</Page>

AssociationLaunching/LaunchFile.xaml.cs

/*
 * 演示如何使用外部程序打開一個文件
 */

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

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

        private async void btnLaunchFile_Click_1(object sender, RoutedEventArgs e)
        {
            /*
             * Launcher - 用於啟動與指定文件相關的應用程序
             *     LaunchFileAsync(IStorageFile file) - 打開指定的文件
             *     LaunchFileAsync(IStorageFile file, LauncherOptions options) - 打開指定的文件
             * 
             * LauncherOptions - 啟動外部應用程序時的相關選項
             *     TreatAsUntrusted - 使用默認應用程序打開指定的文件時,是否彈出安全警告
             *     DisplayApplicationPicker - 是否彈出“打開方式”對話框
             *     UI.InvocationPoint - 指定“打開方式”對話框的顯示位置
             *     
             * 當指定的文件不被任何應用程序支持時,可以用以下下兩種方法處理
             * 1、指定 LauncherOptions.FallbackUri: 打開瀏覽器並跳轉到指定的地址
             * 2、指定 PreferredApplicationDisplayName 和 PreferredApplicationPackageFamilyName
             *    PreferredApplicationDisplayName - 指定在彈出的“在商店搜索”對話框中所顯示的應用程序名稱
             *    PreferredApplicationPackageFamilyName - 用戶點擊“在商店搜索”后,會在商店搜索指定 PackageFamilyName
             */


            // 指定需要打開的文件
            var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(@"Assets\Logo.png");

            // 指定打開文件過程中相關的各種選項
            var options = new Windows.System.LauncherOptions();
            if (radWarning.IsChecked.Value)
            {
                options.TreatAsUntrusted = true;
            }
            if (radOpenWith.IsChecked.Value)
            {
                Point openWithPosition = GetOpenWithPosition(btnLaunchFile);

                options.DisplayApplicationPicker = true;
                options.UI.InvocationPoint = openWithPosition;
            }

            // 使用外部程序打開指定的文件
            bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
            if (success)
            {
                lblMsg.Text = "打開成功";
            }
            else
            {
                lblMsg.Text = "打開失敗";
            }
        }

        // 獲取“打開方式”對話框的顯示位置,即關聯 Button 的左下角點的坐標
        private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element)
        {
            Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null);

            Point desiredLocation = buttonTransform.TransformPoint(new Point());
            desiredLocation.Y = desiredLocation.Y + element.ActualHeight;

            return desiredLocation;
        }
    }
}


2、演示如何使用外部程序打開指定的 Uri
AssociationLaunching/LaunchUri.xaml

<Page
    x:Class="XamlDemo.AssociationLaunching.LaunchUri"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Launcher"
    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" Margin="0 0 0 10" />

            <RadioButton Content="使用默認打開方式打開指定的 Uri" Name="radDefault" GroupName="LaunchType" IsChecked="True" />
            <RadioButton Content="使用默認打開方式打開指定的 Uri,打開前彈出警告框" Name="radWarning" GroupName="LaunchType" />
            <RadioButton Content="選擇指定的打開方式打開指定的 Uri" Name="radOpenWith" GroupName="LaunchType" />
            
            <Button Content="打開一個 uri" Name="btnLaunchUri" Click="btnLaunchUri_Click_1" Margin="0 10 0 0" />
        </StackPanel>
    </Grid>
</Page>

AssociationLaunching/LaunchUri.xaml.cs

/*
 * 演示如何使用外部程序打開指定的 Uri
 */

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

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

        private async void btnLaunchUri_Click_1(object sender, RoutedEventArgs e)
        {
            /*
             * Launcher - 用於啟動與指定 Uri 相關的應用程序
             *     LaunchUriAsync(Uri uri) - 打開指定的 Uri
             *     LaunchUriAsync(Uri uri, LauncherOptions options) - 打開指定的 Uri
             * 
             * LauncherOptions - 啟動外部應用程序時的相關選項
             *     TreatAsUntrusted - 使用默認應用程序打開指定的文件時,是否彈出安全警告
             *     DisplayApplicationPicker - 是否彈出“打開方式”對話框
             *     UI.InvocationPoint - 指定“打開方式”對話框的顯示位置
             *     
             * 當指定的 Uri 不被任何應用程序支持時,可以用以下下兩種方法處理
             * 1、指定 LauncherOptions.FallbackUri: 打開瀏覽器並跳轉到指定的地址
             * 2、指定 PreferredApplicationDisplayName 和 PreferredApplicationPackageFamilyName
             *    PreferredApplicationDisplayName - 指定在彈出的“在商店搜索”對話框中所顯示的應用程序名稱
             *    PreferredApplicationPackageFamilyName - 用戶點擊“在商店搜索”后,會在商店搜索指定 PackageFamilyName
             */

            // 指定需要打開的 Uri
            var uri = new Uri("http://webabcd.cnblogs.com");

            // 指定打開 Uri 過程中相關的各種選項
            var options = new Windows.System.LauncherOptions();
            if (radWarning.IsChecked.Value)
            {
                options.TreatAsUntrusted = true;
            }
            if (radOpenWith.IsChecked.Value)
            {
                Point openWithPosition = GetOpenWithPosition(btnLaunchUri);

                options.DisplayApplicationPicker = true;
                options.UI.InvocationPoint = openWithPosition;
            }

            // 使用外部程序打開指定的 Uri
            bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
            if (success)
            {
                lblMsg.Text = "打開成功";
            }
            else
            {
                lblMsg.Text = "打開失敗";
            }
        }

        // 獲取“打開方式”對話框的顯示位置,即關聯 Button 的左下角點的坐標
        private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element)
        {
            Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null);

            Point desiredLocation = buttonTransform.TransformPoint(new Point());
            desiredLocation.Y = desiredLocation.Y + element.ActualHeight;

            return desiredLocation;
        }
    }
}


3、演示如何關聯指定的文件類型(即用本程序打開指定類型的文件)
AssociationLaunching/FileTypeAssociation.xaml

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

    <Grid Background="Transparent">
        <TextBlock Name="lblMsg" FontSize="24" TextWrapping="Wrap" Margin="120 0 0 0">
            <Run>本程序可以打開 .webabcd 類型的文件</Run>
            <LineBreak />
            <Run>測試方法:在桌面新建一個文本文件,隨便輸一些字符,然后將后綴名改為 .webabcd,最后打開文件,本程序會顯示其文本內容</Run>
        </TextBlock>
    </Grid>
</Page>

AssociationLaunching/FileTypeAssociation.xaml.cs

/*
 * 演示如何關聯指定的文件類型(即用本程序打開指定類型的文件)
 * 
 * 1、在 Package.appxmanifest 中新增一個“文件類型關聯”聲明,並做相關配置
 * 2、在 App.xaml.cs 中 override void OnFileActivated(FileActivatedEventArgs args),以獲取相關的文件信息
 * 
 * FileActivatedEventArgs - 通過打開文件激活應用程序時的事件參數
 *     Files - 相關的文件信息
 *     PreviousExecutionState, Kind, SplashScreen - 各種激活 app 的方式的事件參數基本上都有這些屬性,就不多說了
 */

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

namespace XamlDemo.AssociationLaunching
{
    public sealed partial class FileTypeAssociation : Page
    {
        private FileActivatedEventArgs _fileActivated;

        public FileTypeAssociation()
        {
            this.InitializeComponent();

            this.Loaded += FileTypeAssociation_Loaded;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 獲取 FileActivatedEventArgs 對象
            _fileActivated = e.Parameter as FileActivatedEventArgs;
        }

        async void FileTypeAssociation_Loaded(object sender, RoutedEventArgs e)
        {
            // 獲取文件中的文本內容,並顯示
            if (_fileActivated != null)
            {
                var isf = _fileActivated.Files[0] as IStorageFile;
                lblMsg.Text = await FileIO.ReadTextAsync(isf);
            }
        }
    }
}

App.xaml.cs

// 通過打開文件激活應用程序時所調用的方法
protected override void OnFileActivated(FileActivatedEventArgs args)
{
    Frame rootFrame = new Frame();
    rootFrame.Navigate(typeof(MainPage), args);
    Window.Current.Content = rootFrame;

    Window.Current.Activate();
}


4、演示如何關聯指定的協議(即用本程序處理指定的協議)
AssociationLaunching/ProtocolAssociation.xaml

<Page
    x:Class="XamlDemo.AssociationLaunching.ProtocolAssociation"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.AssociationLaunching"
    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="24">
                <Run>本程序可以處理 webabcd:// 協議</Run>
            </TextBlock>

            <Button Name="btnProtocol" Content="打開自定義協議 webabcd://data" Click="btnProtocol_Click_1" Margin="0 10 0 0" />
        </StackPanel>
    </Grid>
</Page>

AssociationLaunching/ProtocolAssociation.xaml.cs

/*
 * 演示如何關聯指定的協議(即用本程序處理指定的協議)
 * 
 * 1、在 Package.appxmanifest 中新增一個“協議”聲明,並做相關配置
 * 2、在 App.xaml.cs 中 override void OnActivated(IActivatedEventArgs args),以獲取相關的協議信息
 * 
 * ProtocolActivatedEventArgs - 通過協議激活應用程序時的事件參數
 *     Uri - 協議的 uri
 *     PreviousExecutionState, Kind, SplashScreen - 各種激活 app 的方式的事件參數基本上都有這些屬性,就不多說了
 */

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

namespace XamlDemo.AssociationLaunching
{
    public sealed partial class ProtocolAssociation : Page
    {
        private ProtocolActivatedEventArgs _protocolActivated;

        public ProtocolAssociation()
        {
            this.InitializeComponent();

            this.Loaded += ProtocolAssociation_Loaded;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 獲取 ProtocolActivatedEventArgs 對象
            _protocolActivated = e.Parameter as ProtocolActivatedEventArgs;
        }

        void ProtocolAssociation_Loaded(object sender, RoutedEventArgs e)
        {
            // 顯示協議的詳細信息
            if (_protocolActivated != null)
                lblMsg.Text = _protocolActivated.Uri.AbsoluteUri;
        }

        private async void btnProtocol_Click_1(object sender, RoutedEventArgs e)
        {
            // 打開自定義協議 webabcd://data
            var uri = new Uri("webabcd://data");
            await Windows.System.Launcher.LaunchUriAsync(uri);

            // 打開 IE 瀏覽器,在地址欄輸入 webabcd://data,即會打開本程序來處理此協議
        }
    }
}

App.xaml.cs

protected override void OnActivated(IActivatedEventArgs args)
{
    // 通過協議激活應用程序時
    if (args.Kind == ActivationKind.Protocol)
    {
        ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;

        Frame rootFrame = new Frame();
        rootFrame.Navigate(typeof(MainPage), protocolArgs);
        Window.Current.Content = rootFrame;

        Window.Current.Activate();
    }
}



OK
[源碼下載]


免責聲明!

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



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