重新想象 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
[源码下载]

posted @ 2013-06-13 08:55  webabcd  阅读(2949)  评论(12编辑  收藏  举报