重新想象 Windows 8 Store Apps (33) - 关联启动: 使用外部程序打开一个文件或uri, 关联指定的文件类型或协议

简介: 原文:重新想象 Windows 8 Store Apps (33) - 关联启动: 使用外部程序打开一个文件或uri, 关联指定的文件类型或协议[源码下载] 重新想象 Windows 8 Store Apps (33) - 关联启动: 使用外部程序打开一个文件或uri, 关联指定的文件类型或协议...
原文: 重新想象 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
[源码下载]

目录
相关文章
|
2月前
|
Windows
Windows下版本控制器(SVN)-验证是否安装成功+配置版本库+启动服务器端程序
Windows下版本控制器(SVN)-验证是否安装成功+配置版本库+启动服务器端程序
114 2
|
3月前
|
Windows
Windows下版本控制器(SVN)-启动服务器端程序
Windows下版本控制器(SVN)-启动服务器端程序
113 4
|
4月前
|
Linux 网络安全 iOS开发
SecureCRT & SecureFX 9.6.3 for macOS, Linux, Windows - 跨平台的多协议终端仿真和文件传输
SecureCRT & SecureFX 9.6.3 for macOS, Linux, Windows - 跨平台的多协议终端仿真和文件传输
1205 4
SecureCRT & SecureFX 9.6.3 for macOS, Linux, Windows - 跨平台的多协议终端仿真和文件传输
|
3月前
|
C++ Windows
【Function App】本地通过VS Code调试Function时候遇见无法加载文件错误Microsoft.Extensions.Diagnostics.Abstractions
在使用 VS Code 调试 Azure Functions 时,执行 `func host start` 可能因版本冲突报错。错误信息显示 Rpc Initialization Service 启动失败,可能是由于缺少文件或组件导致。解决方法包括:1) 使用 npm 卸载并重新安装 Azure Functions Core Tools;2) 若问题未解决,重新下载安装包(如 func-cli-x64.msi)修复旧版本工具;3) 退出并重启 VS Code,重新加载项目即可恢复正常运行。参考资料链接提供了更多背景信息。
172 1
|
5月前
|
安全 Windows
“由于启动计算机时出现了页面文件配置问题,Windows在你的计算机上创建了一个临时页面文件。。。”的问题解决
本文主要介绍了因清理电脑垃圾文件时误删虚拟内存导致的Windows页面文件配置问题,并提供了详细的解决步骤。问题表现为开机后出现临时页面文件创建的提示弹窗。解决方法包括通过控制面板或快捷键进入高级系统设置,进而调整虚拟内存设置:进入性能选项中的虚拟内存栏,选择自动管理所有驱动器的分页文件大小,最后确认并重启计算机以恢复正常运行。
3512 5
“由于启动计算机时出现了页面文件配置问题,Windows在你的计算机上创建了一个临时页面文件。。。”的问题解决
|
4月前
|
安全 Devops 测试技术
AppSpider 7.5.018 for Windows - Web 应用程序安全测试
AppSpider 7.5.018 for Windows - Web 应用程序安全测试
86 0
AppSpider 7.5.018 for Windows - Web 应用程序安全测试
|
8月前
|
Dart 前端开发
【05】flutter完成注册页面完善样式bug-增加自定义可复用组件widgets-严格规划文件和目录结构-规范入口文件-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
【05】flutter完成注册页面完善样式bug-增加自定义可复用组件widgets-严格规划文件和目录结构-规范入口文件-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
262 75
【05】flutter完成注册页面完善样式bug-增加自定义可复用组件widgets-严格规划文件和目录结构-规范入口文件-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草央千澈
|
7月前
|
安全 JavaScript Java
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
94 12
AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
|
11月前
|
移动开发 开发框架 小程序
uni-app:demo&媒体文件&配置全局的变量(三)
uni-app 是一个使用 Vue.js 构建多平台应用的框架,支持微信小程序、支付宝小程序、H5 和 App 等平台。本文档介绍了 uni-app 的基本用法,包括登录示例、媒体文件处理、全局变量配置和 Vuex 状态管理的实现。通过这些示例,开发者可以快速上手并高效开发多平台应用。
199 0
|
6月前
|
Windows
Windows程序的数字签名证书怎么申请
Windows程序的数字签名证书申请流程包括:准备企业资料(营业执照、税务登记证等),提交申请表及企业资料。经过初审、实名认证和二审后,等待1-5个工作日审核结果。审核通过后,CA机构颁发证书并通过邮件或邮寄方式发送。收到证书后按指南安装并使用签名工具对程序进行数字签名,确保软件完整性和可信度。注意证书有效期、管理和兼容性问题。

热门文章

最新文章