首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 關聯啟動完整指南:檔案/URI 關聯與自訂協定

     編輯:關於.NET

前言

關聯啟動讓應用程式能夠處理特定檔案類型或 URI 協定,也能呼叫外部程式開啟檔案或 URI。本文詳細說明四大核心場景:使用外部程式開啟檔案、使用外部程式開啟 URI、註冊成為特定檔案類型的預設處理程式、註冊成為特定協定的處理程式。

一、使用外部程式開啟檔案

透過 Windows.System.Launcher.LaunchFileAsync 呼叫系統預設處理程式。LauncherOptions 可控制是否顯示安全性警告、是否彈出「開啟方式」選擇器、指定選擇器位置,以及在無對應應用時導向備用 URI 或商店搜尋特定應用。

XAML 介面

<Page x:Class="XamlDemo.AssociationLaunching.LaunchFile" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Launcher" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://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>

程式碼後置

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)
        {
            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 = "開啟失敗";
            }
        }

        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;
        }
    }
}

二、使用外部程式開啟 URI

透過 Windows.System.Launcher.LaunchUriAsync 開啟網址、mailto、自訂協定等。參數與開啟檔案類似,同樣支援 LauncherOptions 完整功能。

XAML 介面

<Page x:Class="XamlDemo.AssociationLaunching.LaunchUri" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Launcher" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://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>

程式碼後置

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)
        {
            var uri = new Uri("https://webabcd.cnblogs.com");
            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;
            }
            bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
            if (success)
            {
                lblMsg.Text = "開啟成功";
            }
            else
            {
                lblMsg.Text = "開啟失敗";
            }
        }

        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;
        }
    }
}

三、關聯指定檔案類型 (成為該類型檔案的處理程式)

  1. 在 Package.appxmanifest 中新增「檔案類型關聯」宣告,設定副檔名 (如 .webabcd)、Content Type、Logo 等。
  2. 在 App.xaml.cs 覆寫 OnFileActivated,接收 FileActivatedEventArgs 取得檔案清單。
  3. 頁面中透過 NavigationEventArgs.Parameter 取得事件參數,讀取檔案內容顯示。

頁面 XAML

<Page x:Class="XamlDemo.AssociationLaunching.FileTypeAssociation" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.Launch" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://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>

頁面程式碼後置

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)
        {
            _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();
}

四、關聯指定協定 (成為該協定的處理程式)

  1. 在 Package.appxmanifest 中新增「協定」宣告,設定協定名稱 (如 webabcd)。
  2. 在 App.xaml.cs 覆寫 OnActivated,判斷 args.Kind == ActivationKind.Protocol,取得 ProtocolActivatedEventArgs 中的 Uri 屬性。
  3. 頁面同樣透過導航參數接收並顯示 URI 內容。

頁面 XAML

<Page x:Class="XamlDemo.AssociationLaunching.ProtocolAssociation" xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:XamlDemo.AssociationLaunching" xmlns:d="https://schemas.microsoft.com/expression/blend/2008" xmlns:mc="https://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>

頁面程式碼後置

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)
        {
            _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)
        {
            var uri = new Uri("webabcd://data");
            await Windows.System.Launcher.LaunchUriAsync(uri);
        }
    }
}

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();
    }
}

總結

  • Launcher.LaunchFileAsync/LaunchUriAsync 是呼叫外部程式的統一入口,LauncherOptions 提供豐富的互動控制。
  • 檔案類型關聯需在 Manifest 宣告副檔名與 Content Type,啟動時透過 OnFileActivated 接收 StorageFile 集合。
  • 協定關聯需在 Manifest 宣告協定名稱,啟動時透過 OnActivated 接收 Uri 參數。
  • 測試時可建立對應副檔名的檔案,或在瀏覽器網址列輸入 webabcd://data 觸發啟動。

[原始碼下載]:https://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved