图解使用Win8Api进行Metro风格的程序开发六----文件关联,双击文件打开程序,通过协议打开程序
我们紧接着上篇,这篇将介绍如何使用Windows.System.Launcher API设置默认打开文件方式,
如何双击文件打开程序,如何通过协议打开程序
-----------------------------------我是华丽的分割线-----------------------------------------
今天我们要用Windows.System.Launcher API设置默认打开文件方式,
如何双击文件打开程序,如何通过协议打开程序
本篇将介绍如下四个方面:
a)使用LaunchFileAsync加载默认的程序
b)使用激活事件处理文件激活
c)使用文件关联加载默认应用程序
d)使用激活事件处理的协议激活
我们的创建的步骤如下:
1)为了组织文件方便,我们先建一个文件夹AssociationLaunching
2)向文件夹中添加如下四个文件:
LaunchFile.xaml,LaunchUri.xaml,
ReceiveFile.xaml,ReceiveUri.xaml
创建方法请参照前一篇.
3)此时的解决方案结构如下:
4)向我们的DataSource添加导航所需要的信息
修改我们的SampleDataSource.cs文件中的SampleDataSource类中的代码,
代码如下:
public SampleDataSource() { #region Group1 var group1 = new SampleDataGroup("FilePicker", "Use Windows.Storage.Pickers API", "Access and save files using the file picker", "Assets/FilePicker.jpg", ""); group1.Items.Add(new SampleDataItem("FilePicker-PickASinglePhoto", "Pick a single photo", "only one file can selected,file type is jpg,jpeg,png", "Assets/FilePicker.jpg", "only one file can selected ", "", group1, typeof(PickASinglePhoto))); group1.Items.Add(new SampleDataItem("FilePicker-PickMultipleFiles", "Pick multiple files", "you can pick multiple files", "Assets/FilePicker.jpg", "pick multiple files", "", group1, typeof(PickMultipleFiles))); group1.Items.Add(new SampleDataItem("FilePicker-PickAFolder", "Pick a folder", "you can pick a folder", "Assets/FilePicker.jpg", "Pick a folder", "", group1, typeof(PickAFolder))); group1.Items.Add(new SampleDataItem("FilePicker-SaveAFile", "Save a file", "you can save a file", "Assets/FilePicker.jpg", "Save a file", "", group1, typeof(SaveAFile))); this.AllGroups.Add(group1); #endregion #region Group2 var group2 = new SampleDataGroup("FileAceess", "Using Windows.Storage API", "File access", "Assets/FileAccess.jpg", ""); group2.Items.Add(new SampleDataItem("FileAceess-CreatingAFile", "Create a file", "Using CreateFileAsync Create a file", "Assets/FileAccess.jpg", "Using CreateFileAsync", "", group2, typeof(CreatingAFile))); group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingText", "Write And Read A Text", "Using WriteTextAsync,ReadTextAsync Write And Read Text", "Assets/FileAccess.jpg", "Using WriteTextAsync,ReadTextAsync", "", group2, typeof(WritingAndReadingText))); group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingBytes", "Writing and reading bytes in a file", "Using WriteBufferAsync,ReadBufferAsync Write And Read bytes", "Assets/FileAccess.jpg", "Using WriteBufferAsync,ReadBufferAsync", "", group2, typeof(WritingAndReadingBytes))); group2.Items.Add(new SampleDataItem("FileAceess-WritingAndReadingUsingStream", "Writing and reading using a stream", "Using OpenAsync Writing and reading using a stream", "Assets/FileAccess.jpg", "Using OpenAsync", "", group2, typeof(WritingAndReadingUsingStream))); group2.Items.Add(new SampleDataItem("FileAceess-DisplayingFileProperties", "Displaying file properties", "Using GetBasicPropertiesAsync Get File Properties", "Assets/FileAccess.jpg", "Using GetBasicPropertiesAsync", "", group2, typeof(DisplayingFileProperties))); group2.Items.Add(new SampleDataItem("FileAceess-PersistingAccess", "Persisting access to a storage item for future use", "Using MostRecentlyUsedList", "Assets/FileAccess.jpg", "Using MostRecentlyUsedList", "", group2, typeof(PersistingAccess))); group2.Items.Add(new SampleDataItem("FileAceess-CopyAFile", "Copy a file", "Using CopyAsync Copy a file", "Assets/FileAccess.jpg", "Using CopyAsync", "", group2, typeof(CopyAFile))); group2.Items.Add(new SampleDataItem("FileAceess-DeleteAFile", "Delete a file", "Using DeleteAsync Delete a file", "Assets/FileAccess.jpg", "Using DeleteAsync", "", group2, typeof(DeleteAFile))); this.AllGroups.Add(group2); #endregion #region Group3 var group3 = new SampleDataGroup("AccountPictureName", "Use Windows.System.UserProfile API", "Account Picture Name", "Assets/AccountPictureName.jpg", ""); group3.Items.Add(new SampleDataItem("AccountPictureName-GetUserDisplayName", "Get User DisplayName", "Use UserInformation.GetDisplayNameAsync Get User DisplayName", "Assets/AccountPictureName.jpg", "Use UserInformation.GetDisplayNameAsync", "", group3, typeof(GetUserDisplayName))); group3.Items.Add(new SampleDataItem("AccountPictureName-GetUserFirstLastName", "Get First Last Name", "Use UserInformation.GetFirstNameAsync,GetLastNameAsync Get First Name", "Assets/AccountPictureName.jpg", "Use UserInformation.GetFirstNameAsync ", "", group3, typeof(GetUserFirstLastName))); group3.Items.Add(new SampleDataItem("AccountPictureName-GetAccountPicture", "Get Account Picture", "Use UserInformation.GetAccountPicture Get Account Picture", "Assets/AccountPictureName.jpg", "Use UserInformation.GetAccountPicture", "", group3, typeof(GetAccountPicture))); group3.Items.Add(new SampleDataItem("AccountPictureName-SetAccountPictureAndListen", "Set AccountPicture And Listen", "Use UserInformation.SetAccountPicturesAsync Set AccountPicture", "Assets/AccountPictureName.jpg", "Use UserInformation.SetAccountPicturesAsync", "", group3, typeof(SetAccountPictureAndListen))); this.AllGroups.Add(group3); #endregion #region Group4 var group4 = new SampleDataGroup("ApplicationSettings", "ApplicationSettings", " Use the Windows.UI.ApplicationSettings namespace and WinJS.UI.SettingsFlyout", "Assets/ApplicationSettings.jpg", ""); group4.Items.Add(new SampleDataItem("ApplicationSettings-Default", "Default behavior with no settings integration", "Default behavior ", "Assets/ApplicationSettings.jpg", "Default behavior with no settings integration", "", group4, typeof(Default))); group4.Items.Add(new SampleDataItem("ApplicationSettings-AddSettings", "Add settings commands to the settings charm", "Add settings", "Assets/ApplicationSettings.jpg", "Add settings commands to the settings charm ", "", group4, typeof(AddSettings))); this.AllGroups.Add(group4); #endregion #region Group5 var Group5 = new SampleDataGroup("AssociationLaunching", "Use Windows.System.Launcher API", "Association Launching", "Assets/AssociationLaunching.jpg", ""); Group5.Items.Add(new SampleDataItem("AssociationLaunching-LaunchFile", "Launching a file", "Use Windows.System.Launcher.LaunchFileAsync", "Assets/AssociationLaunching.jpg", "Use Windows.System.Launcher.LaunchFileAsync", "", Group5, typeof(LaunchFile))); Group5.Items.Add(new SampleDataItem("AssociationLaunching-LaunchUri", "Launching a URI", "Use Windows.System.Launcher.LaunchUriAsync", "Assets/AssociationLaunching.jpg", "Use Windows.System.Launcher.LaunchUriAsync", "", Group5, typeof(LaunchUri))); Group5.Items.Add(new SampleDataItem("AssociationLaunching-ReceiveFile", "Receiving a file", "Receiving a file", "Assets/AssociationLaunching.jpg", "Receiving a file", "", Group5, typeof(ReceiveFile))); Group5.Items.Add(new SampleDataItem("AssociationLaunching-ReceiveUri", "Receiving a URI", "Receiving a URI", "Assets/AssociationLaunching.jpg", "Receiving a URI", "", Group5, typeof(ReceiveUri))); this.AllGroups.Add(Group5); #endregion }
5)我们的导航这样就做好了,效果图:
点击 AssociationLaunching
6)使用LaunchFileAsync加载默认的程序
我们使用Windows.System.Launcher.LaunchFileAsync来加载文件,使用Windows.System.LauncherOptions来指示是否提示安全警告
修改我们的LaunchFile.xaml的xaml:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch Default Handler</Bold> button will launch a .png file with the default handler installed on the system.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch with Warning</Bold> button sets <Bold>Windows.System.LauncherOptions.TreatAsUntrusted</Bold> to true, which results in a warning prompt being shown prior to launching the file.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch Open With</Bold> button will launch the 'Open With' dialog that lets the user chose the handler for the .png file.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Pick and Launch</Bold> button will launch the file picker that lets the user pick the file to launch. The picked file is then launched.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">All variations use <Bold>Windows.System.LaunchFileAsync</Bold>.</TextBlock> <StackPanel Orientation="Horizontal" Margin="0,10,0,0"> <Button x:Name="LaunchFileButton" Content="Launch Default Handler" Click="LaunchFileButton_Click" Margin="0,0,10,0"/> <Button x:Name="LaunchFileWithWarningButton" Content="Launch with Warning" Click="LaunchFileWithWarningButton_Click" Margin="0,0,10,0"/> <Button x:Name="LaunchFileOpenWithButton" Content="Launch Open With" Click="LaunchFileOpenWithButton_Click" Margin="0,0,10,0"/> <Button x:Name="PickAndLaunchFileButton" Content="Pick and Launch" Click="PickAndLaunchFileButton_Click" Margin="0,0,10,0"/> </StackPanel> </StackPanel> <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1"> <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/> </Grid> </Grid>
修改我们的后台代码:
public sealed partial class LaunchFile : Page { string fileToLaunch = @"Assets\logo.jpg"; public LaunchFile() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { } private async void LaunchFileButton_Click(object sender, RoutedEventArgs e) { // First, get the image file from the package's image directory. var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch); if (file != null) { // Next, launch the file. bool success = await Windows.System.Launcher.LaunchFileAsync(file); if (success) { OutputTextBlock.Text = "File launched: " + file.Name; } else { OutputTextBlock.Text = "File launch failed."; } } else { OutputTextBlock.Text = "Could not find file to launch."; } } // Launch a .jpg file that came with the package. Show a warning prompt. private async void LaunchFileWithWarningButton_Click(object sender, RoutedEventArgs e) { // First, get the image file from the package's image directory. var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch); if (file != null) { // Next, configure the warning prompt. var options = new Windows.System.LauncherOptions(); options.TreatAsUntrusted = true; // Finally, launch the file. bool success = await Windows.System.Launcher.LaunchFileAsync(file, options); if (success) { OutputTextBlock.Text = "File launched: " + file.Name; } else { OutputTextBlock.Text = "File launch failed."; } } else { OutputTextBlock.Text = "Could not find file to launch."; } } // Launch a .jpg file that came with the package. Show an Open With dialog that lets the user chose the handler to use. private async void LaunchFileOpenWithButton_Click(object sender, RoutedEventArgs e) { // First, get the image file from the package's image directory. var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch); if (file != null) { // Calulcate the position for the Open With dialog. // An alternative to using the point is to set the rect of the UI element that triggered the launch. Point openWithPosition = GetOpenWithPosition(LaunchFileOpenWithButton); // Next, configure the Open With dialog. var options = new Windows.System.LauncherOptions(); options.DisplayApplicationPicker = true; options.UI.InvocationPoint = openWithPosition; options.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below; // Finally, launch the file. bool success = await Windows.System.Launcher.LaunchFileAsync(file, options); if (success) { OutputTextBlock.Text = "File launched: " + file.Name; } else { OutputTextBlock.Text = "File launch failed."; } } else { OutputTextBlock.Text = "Could not find file to launch."; } } // Have the user pick a file, then launch it. private async void PickAndLaunchFileButton_Click(object sender, RoutedEventArgs e) { // First, get a file via the picker. var openPicker = new Windows.Storage.Pickers.FileOpenPicker(); openPicker.FileTypeFilter.Add("*"); Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { // Next, launch the file. bool success = await Windows.System.Launcher.LaunchFileAsync(file); if (success) { OutputTextBlock.Text = "File launched: " + file.Name; } else { OutputTextBlock.Text = "File launch failed."; } } else { OutputTextBlock.Text = "No file was picked."; } } // The Open With dialog should be displayed just under the element that triggered it. private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element) { Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null); Point desiredLocation = buttonTransform.TransformPoint(new Point()); desiredLocation.X = desiredLocation.X + element.ActualWidth / 2; desiredLocation.Y = desiredLocation.Y + element.ActualHeight; return desiredLocation; } }
效果图:
点击第一个按钮:
点击第二个按钮:
点击第三个按钮:
点击第四个按钮:
7)使用激活事件处理文件激活
我们使用Windows.System.Launcher.LaunchUriAsync来加载网址,使用Windows.System.LauncherOptions来指示是否提示安全警告
修改LaunchUri.xaml的xaml:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch Default Handler</Bold> button will launch the URI http://www.bing.com with the default handler installed on the system.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch with Warning</Bold> button sets <Bold>Windows.System.LauncherOptions.TreatAsUntrusted</Bold> to true, which results in a warning prompt being shown prior to launching the URI.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">Clicking on the <Bold>Launch Open With</Bold> button will launch the 'Open With' dialog that lets the user chose the handler for the URI.</TextBlock> <TextBlock TextWrapping="Wrap" Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left">All variations use <Bold>Windows.System.LaunchUriAsync</Bold>.</TextBlock> <StackPanel Orientation="Horizontal" Margin="0,10,0,0"> <Button x:Name="LaunchUriButton" Content="Launch Default Handler" Click="LaunchUriButton_Click" Margin="0,0,10,0"/> <Button x:Name="LaunchUriWithWarningButton" Content="Launch with Warning" Click="LaunchUriWithWarningButton_Click" Margin="0,0,10,0"/> <Button x:Name="LaunchUriOpenWithButton" Content="Launch Open With" Click="LaunchUriOpenWithButton_Click" Margin="0,0,10,0"/> </StackPanel> </StackPanel> <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1"> <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/> </Grid> </Grid>
修改后台代码:
public sealed partial class LaunchUri : Page { string uriToLaunch = @"http://www.cnblogs.com/refactor"; public LaunchUri() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { } // Launch a URI. private async void LaunchUriButton_Click(object sender, RoutedEventArgs e) { // Create the URI to launch from a string. var uri = new Uri(uriToLaunch); // Launch the URI. bool success = await Windows.System.Launcher.LaunchUriAsync(uri); if (success) { OutputTextBlock.Text = "URI launched: " + uri.AbsoluteUri; } else { OutputTextBlock.Text = "URI launch failed."; } } // Launch a URI. Show a warning prompt. private async void LaunchUriWithWarningButton_Click(object sender, RoutedEventArgs e) { // Create the URI to launch from a string. var uri = new Uri(uriToLaunch); // Configure the warning prompt. var options = new Windows.System.LauncherOptions(); options.TreatAsUntrusted = true; // Launch the URI. bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options); if (success) { OutputTextBlock.Text = "URI launched: " + uri.AbsoluteUri; } else { OutputTextBlock.Text = "URI launch failed."; } } // Launch a URI. Show an Open With dialog that lets the user chose the handler to use. private async void LaunchUriOpenWithButton_Click(object sender, RoutedEventArgs e) { // Create the URI to launch from a string. var uri = new Uri(uriToLaunch); // Calulcate the position for the Open With dialog. // An alternative to using the point is to set the rect of the UI element that triggered the launch. Point openWithPosition = GetOpenWithPosition(LaunchUriOpenWithButton); // Next, configure the Open With dialog. var options = new Windows.System.LauncherOptions(); options.DisplayApplicationPicker = true; options.UI.InvocationPoint = openWithPosition; options.UI.PreferredPlacement = Windows.UI.Popups.Placement.Below; // Launch the URI. bool success = await Windows.System.Launcher.LaunchUriAsync(uri, options); if (success) { OutputTextBlock.Text = "URI launched: " + uri.AbsoluteUri; } else { OutputTextBlock.Text = "URI launch failed."; } } // The Open With dialog should be displayed just under the element that triggered it. private Windows.Foundation.Point GetOpenWithPosition(FrameworkElement element) { Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null); Point desiredLocation = buttonTransform.TransformPoint(new Point()); desiredLocation.X = desiredLocation.X + element.ActualWidth / 2; desiredLocation.Y = desiredLocation.Y + element.ActualHeight; return desiredLocation; } }
效果图和6差不多
8)使用文件关联加载默认应用程序
我们使用FileActivatedEventArgs,来处理双击后缀名为refactor的文件,默认打开我们的程序
修改ReceiveFile.xaml的xaml:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel> <TextBlock TextWrapping="Wrap" Text="In Windows Explorer, create a file with a .refactorblog extension. Double-click the file." Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left"/> </StackPanel> <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1"> <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/> </Grid> </Grid>
修改后台代码:
public sealed partial class ReceiveFile : Page { public ReceiveFile() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { FileActivatedEventArgs FileEvent = e.Parameter as FileActivatedEventArgs; if (FileEvent != null) { OutputTextBlock.Text = "File activation received. The number of files received is " + FileEvent.Files.Count + ". The first received file is " + FileEvent.Files[0].Name + "."; } } }
修改App.xaml.cs文件:
// Handle file activations. protected override void OnFileActivated(FileActivatedEventArgs args) { var rootFrame = new Frame(); rootFrame.Navigate(typeof(ItemsPage), "AllGroups"); ItemsPage ip = rootFrame.Content as ItemsPage; //此处只做演示,实际应该将AssociationLaunching囧FileActivated写成类,这里用 //汉字 囧 进行分割 ip.Frame.Navigate(typeof(SplitPage), "AssociationLaunching囧FileActivated"); SplitPage p = rootFrame.Content as SplitPage; Window.Current.Content = rootFrame; p.LoadFrame(typeof(Win8Api.AssociationLaunching.ReceiveFile),args); Window.Current.Activate(); }
修改SplitPage.cs文件,加一个LoadFrame的重载:
/// <summary> /// 创建此分布类是为了方便添加自定义的方法,这样使我们的代码可读性高 /// </summary> public sealed partial class SplitPage : Win8Api.Common.LayoutAwarePage { /// <summary> /// 创建一个Frame,实例化在SplitPage的构造函数内 /// </summary> private Frame ContentFrame = null; /// <summary> /// Frame进行导航的方法 /// </summary> /// <param name="classType">要导航到页面的类型</param> public void LoadFrame(Type classType) { ContentFrame.Navigate(classType, this); } /// <summary> /// Frame进行导航的方法 /// </summary> /// <param name="classType">要导航到页面的类型</param> /// <param name="obj">导航参数</param> public void LoadFrame(Type classType,object obj) { ContentFrame.Navigate(classType, obj); } }
修改SplitPage.xaml.cs文件:
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // TODO: Create an appropriate data model for your problem domain to replace the sample data string[] arrParameter = ((String)navigationParameter).Split('囧'); string strType = ""; if (arrParameter.Length>1) { navigationParameter = arrParameter[0]; strType = arrParameter[1]; } var group = SampleDataSource.GetGroup((String)navigationParameter); this.DefaultViewModel["Group"] = group; this.DefaultViewModel["Items"] = group.Items; if (pageState == null) { // When this is a new page, select the first item automatically unless logical page // navigation is being used (see the logical page navigation #region below.) if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null) { this.itemsViewSource.View.MoveCurrentToFirst(); } if (strType == "FileActivated") { this.itemsViewSource.View.MoveCurrentToPosition(2); } } else { // Restore the previously saved state associated with this page if (pageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null) { var selectedItem = SampleDataSource.GetItem((String)pageState["SelectedItem"]); this.itemsViewSource.View.MoveCurrentTo(selectedItem); } } }
修改我们的Package.appxmanifest,如图:
效果图如下:
当我们双击桌面的refactor.refactor文件时:
9)使用激活事件处理的协议激活
我们使用ProtocolActivatedEventArgs,来处理在协议打开我们的程序
修改ReceiveUri.xaml的xaml:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel> <TextBlock TextWrapping="Wrap" Text="In Windows Explorer, type 'refactor://www.cnblogs.com/refactor' into the address bar and press enter." Style="{StaticResource SubheaderTextStyle}" HorizontalAlignment="Left"/> </StackPanel> <Grid x:Name="Output" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1"> <TextBlock x:Name="OutputTextBlock" Style="{StaticResource SubheaderTextStyle}" TextWrapping="Wrap"/> </Grid> </Grid>
修改后台代码:
public sealed partial class ReceiveUri : Page { public ReceiveUri() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { ProtocolActivatedEventArgs ProtocolEvent = e.Parameter as ProtocolActivatedEventArgs; if (ProtocolEvent != null) { OutputTextBlock.Text = "Protocol activation received. The received URI is " + ProtocolEvent.Uri.AbsoluteUri + "."; } } }
修改修改App.xaml.cs文件:
// Handle protocol activations. protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs; var rootFrame = new Frame(); rootFrame.Navigate(typeof(ItemsPage), "AllGroups"); ItemsPage ip = rootFrame.Content as ItemsPage; ip.Frame.Navigate(typeof(SplitPage), "AssociationLaunching囧ProtocolActivated"); SplitPage p = rootFrame.Content as SplitPage; Window.Current.Content = rootFrame; p.LoadFrame(typeof(Win8Api.AssociationLaunching.ReceiveUri), protocolArgs); } Window.Current.Activate(); }
修改SplitPage.xaml.cs文件:
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { // TODO: Create an appropriate data model for your problem domain to replace the sample data string[] arrParameter = ((String)navigationParameter).Split('囧'); string strType = ""; if (arrParameter.Length>1) { navigationParameter = arrParameter[0]; strType = arrParameter[1]; } var group = SampleDataSource.GetGroup((String)navigationParameter); this.DefaultViewModel["Group"] = group; this.DefaultViewModel["Items"] = group.Items; if (pageState == null) { // When this is a new page, select the first item automatically unless logical page // navigation is being used (see the logical page navigation #region below.) if (!this.UsingLogicalPageNavigation() && this.itemsViewSource.View != null) { this.itemsViewSource.View.MoveCurrentToFirst(); } if (strType == "FileActivated") { this.itemsViewSource.View.MoveCurrentToPosition(2); } if (strType == "ProtocolActivated") { this.itemsViewSource.View.MoveCurrentToPosition(3); } } else { // Restore the previously saved state associated with this page if (pageState.ContainsKey("SelectedItem") && this.itemsViewSource.View != null) { var selectedItem = SampleDataSource.GetItem((String)pageState["SelectedItem"]); this.itemsViewSource.View.MoveCurrentTo(selectedItem); } } }
修改我们的Package.appxmanifest,如图:
效果图:
输入:refactor://www.cnblogs.com/refactor 回车:
未完待续,敬请期待...
转载请注明出处:http://www.cnblogs.com/refactor/