關聯啟動讓應用程式能夠處理特定檔案類型或 URI 協定,也能呼叫外部程式開啟檔案或 URI。本文詳細說明四大核心場景:使用外部程式開啟檔案、使用外部程式開啟 URI、註冊成為特定檔案類型的預設處理程式、註冊成為特定協定的處理程式。
透過 Windows.System.Launcher.LaunchFileAsync 呼叫系統預設處理程式。LauncherOptions 可控制是否顯示安全性警告、是否彈出「開啟方式」選擇器、指定選擇器位置,以及在無對應應用時導向備用 URI 或商店搜尋特定應用。
<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;
}
}
}
透過 Windows.System.Launcher.LaunchUriAsync 開啟網址、mailto、自訂協定等。參數與開啟檔案類似,同樣支援 LauncherOptions 完整功能。
<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;
}
}
}
Package.appxmanifest 中新增「檔案類型關聯」宣告,設定副檔名 (如 .webabcd)、Content Type、Logo 等。App.xaml.cs 覆寫 OnFileActivated,接收 FileActivatedEventArgs 取得檔案清單。NavigationEventArgs.Parameter 取得事件參數,讀取檔案內容顯示。<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);
}
}
}
}
protected override void OnFileActivated(FileActivatedEventArgs args)
{
Frame rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args);
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
Package.appxmanifest 中新增「協定」宣告,設定協定名稱 (如 webabcd)。App.xaml.cs 覆寫 OnActivated,判斷 args.Kind == ActivationKind.Protocol,取得 ProtocolActivatedEventArgs 中的 Uri 屬性。<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);
}
}
}
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 提供豐富的互動控制。OnFileActivated 接收 StorageFile 集合。OnActivated 接收 Uri 參數。webabcd://data 觸發啟動。