Проблема:
У меня есть тестовый проект UWP, который просто выполняет одно: он открывает тестовый файл. html в браузере с помощью Launcher.LaunchFileAsyn c.
Проблема в том, что я не могу заставить его работать, если мой браузер по умолчанию отличается от Edge! Кроме того, это не будет работать, если я дам ему LauncherOptions w / DisplayApplicationPicker со значением true. Это ошибка UWP?!
Что работает: если для браузера по умолчанию установлен Edge, файл html будет корректно запускаться
Windows 10 ОС: Настройки-> Приложения-> Приложения по умолчанию-> Браузер установлен на «Microsoft Edge»
Код:
private async Task<IStorageFile> GetHtmlFileToLaunch()
{
this.HtmlText = "Launch Html File in Default App";
// First, get the image file from the package's image directory.
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(htmlFileToLaunch);
//Can't launch files directly from install folder so copy it over
//to temporary folder first
return await file.CopyAsync(ApplicationData.Current.TemporaryFolder, "filetolaunch.html", NameCollisionOption.ReplaceExisting);
}
private async void HtmlButton_Click(object sender, RoutedEventArgs e)
{
// Launch the file.
bool success = await Launcher.LaunchFileAsync(htmlFile);
if (success)
{
Debug.WriteLine("File launch succeeded.");
}
else
{
Debug.WriteLine("File launch failed.");
}
}
Что не работает: Настройка браузер по умолчанию на Chrome не запускается
Windows 10 ОС: Настройки-> Приложения-> Стандартные приложения-> Браузер установлен на "Google Chrome"
Код: точно такой же код, как указано выше! Выше Debug.Writeline возвращает «Ошибка запуска файла».
Что также не работает: Установка DisplayActionPicker = true для LauncherOptions ( Документированная рекомендация Microsoft )
Windows 10 ОС: Настройки-> Приложения-> Приложения по умолчанию-> Браузер установлен на «Microsoft Edge»
Код:
private async void HtmlButton_Click(object sender, RoutedEventArgs e)
{
// Specify a picker (according to MSFT documentation)
var launcherOptions = new LauncherOptions() { DisplayApplicationPicker = true };
// Launch the file.
bool success = await Launcher.LaunchFileAsync(htmlFile, launcherOptions);
if (success)
{
Debug.WriteLine("File launch succeeded.");
}
else
{
Debug.WriteLine("File launch failed.");
}
}
В Резюме: Являются ли эти два нерабочих случая ошибками UWP? Кто-нибудь в Microsoft может подтвердить? Я хочу, чтобы пользователь мог запускать файл html, используя свой браузер по умолчанию, а не Microsoft Edge.
Другие сведения о системе:
OS: Windows 10 1909
IDE: Visual Studio Pro 2019 16.5.1
UWP Target Version: 17763
Обновлено 2020/04 / 13: Полный исходный код ниже
Сначала создайте приложение C# UWP Blank Page
test. html: добавьте это в вашу папку «Активы», «Создать действие» «Содержимое» и «Не копировать»
<html>
<body>
<h1>THIS IS A TEST PAGE</h1>
</body>
</html>
MainPage.xaml: отредактируйте этот код xaml
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button x:Name="PngButton" Content="{Binding PngText}" Click="PngButton_Click" Margin="10"/>
<Button x:Name="HtmlButton" Content="{Binding HtmlText}" Click="HtmlButton_Click" Margin="10"/>
</StackPanel>
</Grid>
</Page>
MainPage.xaml.cs: отредактируйте выделенный код следующим образом
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
private string fileToLaunch = @"Assets\StoreLogo.png";
private string htmlFileToLaunch = @"Assets\test.html";
private string pngText;
private string htmlText;
private IStorageFile pngFile;
private IStorageFile htmlFile;
public MainPage()
{
this.InitializeComponent();
this.DataContext = this;
this.Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
// THIS ONE WORKS!
pngFile = await GetPngFileToLaunch();
// THIS ONE DOES NOT WORK!
htmlFile = await GetHtmlFileToLaunch();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public string PngText { get => this.pngText; set { this.pngText = value; OnPropertyChanged(); } }
public string HtmlText { get => this.htmlText; set { this.htmlText = value; OnPropertyChanged(); } }
private async Task<IStorageFile> GetPngFileToLaunch()
{
this.PngText = "Launch Png in Default App";
// First, get the image file from the package's image directory.
pngFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch);
//Can't launch files directly from install folder so copy it over
//to temporary folder first
return await pngFile.CopyAsync(ApplicationData.Current.TemporaryFolder, "filetolaunch.png", NameCollisionOption.ReplaceExisting);
}
private async Task<IStorageFile> GetHtmlFileToLaunch()
{
this.HtmlText = "Launch Html File in Default App";
// First, get the image file from the package's image directory.
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(htmlFileToLaunch);
//Can't launch files directly from install folder so copy it over
//to temporary folder first
return await file.CopyAsync(ApplicationData.Current.TemporaryFolder, "filetolaunch.html", NameCollisionOption.ReplaceExisting);
}
private async void PngButton_Click(object sender, RoutedEventArgs e)
{
// Launch the file.
bool success = await Launcher.LaunchFileAsync(pngFile);
if (success)
{
Debug.WriteLine("File launch succeeded.");
}
else
{
Debug.WriteLine("File launch failed.");
}
}
private async void HtmlButton_Click(object sender, RoutedEventArgs e)
{
// Specify a picker (according to MSFT documentation)
var launcherOptions = new LauncherOptions() { DisplayApplicationPicker = true };
// Launch the file.
bool success = await Launcher.LaunchFileAsync(htmlFile, launcherOptions);
if (success)
{
Debug.WriteLine("File launch succeeded.");
}
else
{
Debug.WriteLine("File launch failed.");
}
}
}
}