如何通过WPF中的按钮启动UWP应用程序

yftpprvb  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(202)

如果我直接在Visual Studio中启动我的UWP应用程序(WLAN连接器),它工作正常。但是,如果我尝试在WPF程序中启动它,它将以正确的大小打开UWP窗口,但它只显示标准的splashscreen,它不会启动程序?我不知道怎么了?
安装Nuget PCage:NUGET Microsoft.Toolkit.Wpf.UI.XamlHost NUGET Microsoft.Windows.SDK.Contracts .NET 4.8
希望有人比我更有UWP的经验。谢啦,谢啦
下面你会发现洞项目,WPF启动程序和UWP应用程序,将无法从WPF应用程序正确启动,也许有人可以帮助我:
UWP应用程序(WLAN连接器)

App.xaml.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices.WindowsRuntime;
  6. using Windows.ApplicationModel;
  7. using Windows.ApplicationModel.Activation;
  8. using Windows.Foundation;
  9. using Windows.Foundation.Collections;
  10. using Windows.UI.Xaml;
  11. using Windows.UI.Xaml.Controls;
  12. using Windows.UI.Xaml.Controls.Primitives;
  13. using Windows.UI.Xaml.Data;
  14. using Windows.UI.Xaml.Input;
  15. using Windows.UI.Xaml.Media;
  16. using Windows.UI.Xaml.Navigation;
  17. using Windows.UI;
  18. using Windows.UI.ViewManagement;
  19. using Windows.ApplicationModel.Core;
  20. namespace WLANConnectorUWP
  21. {
  22. /// <summary>
  23. /// Provides application-specific behavior to supplement the default Application class.
  24. /// </summary>
  25. sealed partial class App : Application
  26. {
  27. /// <summary>
  28. /// Initializes the singleton application object. This is the first line of authored code
  29. /// executed, and as such is the logical equivalent of main() or WinMain().
  30. /// </summary>
  31. public App()
  32. {
  33. this.InitializeComponent();
  34. this.Suspending += OnSuspending;
  35. }
  36. /// <summary>
  37. /// Invoked when the application is launched normally by the end user. Other entry points
  38. /// will be used such as when the application is launched to open a specific file.
  39. /// </summary>
  40. /// <param name="e">Details about the launch request and process.</param>
  41. protected override void OnLaunched(LaunchActivatedEventArgs e)
  42. {
  43. Frame rootFrame = Window.Current.Content as Frame;
  44. // Do not repeat app initialization when the Window already has content,
  45. // just ensure that the window is active
  46. if (rootFrame == null)
  47. {
  48. // Create a Frame to act as the navigation context and navigate to the first page
  49. rootFrame = new Frame();
  50. rootFrame.SizeChanged += RootFrame_SizeChanged;
  51. Window.Current.Content = rootFrame;
  52. if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
  53. {
  54. //TODO: Load state from previously suspended application
  55. }
  56. // Place the frame in the current Window
  57. Window.Current.Content = rootFrame;
  58. }
  59. if (e.PrelaunchActivated == false)
  60. {
  61. if (rootFrame.Content == null)
  62. {
  63. // When the navigation stack isn't restored navigate to the first page,
  64. // configuring the new page by passing required information as a navigation
  65. // parameter
  66. rootFrame.Navigate(typeof(MainPage), e.Arguments);
  67. }
  68. // Ensure the current window is active
  69. ApplicationView.PreferredLaunchViewSize = new Size(300, 300);
  70. ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
  71. var view = ApplicationView.GetForCurrentView();
  72. var titleBar = view.TitleBar;
  73. if (titleBar != null)
  74. {
  75. titleBar.ButtonBackgroundColor = Colors.Transparent;
  76. titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
  77. titleBar.ButtonForegroundColor = Colors.Transparent;
  78. titleBar.ButtonInactiveForegroundColor = Colors.Transparent;
  79. titleBar.BackgroundColor = Colors.Transparent;
  80. titleBar.ForegroundColor = Colors.Transparent;
  81. titleBar.InactiveBackgroundColor = Colors.Transparent;
  82. titleBar.InactiveForegroundColor = Colors.Transparent;
  83. CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;
  84. }
  85. Window.Current.Activate();
  86. }
  87. }
  88. /// <summary>
  89. /// Invoked when Navigation to a certain page fails
  90. /// </summary>
  91. /// <param name="sender">The Frame which failed navigation</param>
  92. /// <param name="e">Details about the navigation failure</param>
  93. void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
  94. {
  95. throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
  96. }
  97. /// <summary>
  98. /// Invoked when application execution is being suspended. Application state is saved
  99. /// without knowing whether the application will be terminated or resumed with the contents
  100. /// of memory still intact.
  101. /// </summary>
  102. /// <param name="sender">The source of the suspend request.</param>
  103. /// <param name="e">Details about the suspend request.</param>
  104. private void OnSuspending(object sender, SuspendingEventArgs e)
  105. {
  106. var deferral = e.SuspendingOperation.GetDeferral();
  107. //TODO: Save application state and stop any background activity
  108. deferral.Complete();
  109. }
  110. private void RootFrame_SizeChanged(object sender, SizeChangedEventArgs e)
  111. {
  112. ApplicationView.GetForCurrentView().TryResizeView(new Size(300, 300));
  113. }
  114. }
  115. }

字符串

MainPage.xaml:

  1. <Page
  2. x:Class="WLANConnectorUWP.MainPage"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:WLANConnectorUWP"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d"
  9. Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="300" Height="200">
  10. <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
  11. <ComboBox x:Name="AvailableNetworksComboBox" Width="200" Header="WLAN-Netzwerke"/>
  12. <TextBox x:Name="PasswordTextBox" Width="200" Header="Passwort" Margin="0,10,0,0"/>
  13. <Button x:Name="ConnectButton" Width="200" Content="Verbinden" Margin="0,10,0,0" Click="ConnectButton_Click"/>
  14. </StackPanel>
  15. </Page>

MainPage.xaml.cs

  1. using System;
  2. using System.Linq;
  3. using Windows.UI.Xaml;
  4. using Windows.UI.Xaml.Controls;
  5. using Windows.Devices.Enumeration;
  6. using Windows.Devices.WiFi;
  7. using Windows.Security.Credentials;
  8. using Windows.UI.Popups;
  9. // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
  10. namespace WLANConnectorUWP
  11. {
  12. /// <summary>
  13. /// An empty page that can be used on its own or navigated to within a Frame.
  14. /// </summary>
  15. public sealed partial class MainPage : Page
  16. {
  17. private WiFiAdapter _wifiAdapter;
  18. public MainPage()
  19. {
  20. InitializeComponent();
  21. InitializeWiFiAdapter();
  22. }
  23. private async void InitializeWiFiAdapter()
  24. {
  25. var access = await WiFiAdapter.RequestAccessAsync();
  26. if (access != WiFiAccessStatus.Allowed)
  27. {
  28. await new MessageDialog("Zugriff auf WLAN-Adapter nicht erlaubt").ShowAsync();
  29. return;
  30. }
  31. var result = await DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
  32. if (result.Count == 0)
  33. {
  34. await new MessageDialog("Kein WLAN-Adapter gefunden").ShowAsync();
  35. return;
  36. }
  37. _wifiAdapter = await WiFiAdapter.FromIdAsync(result.First().Id);
  38. await _wifiAdapter.ScanAsync();
  39. foreach (var network in _wifiAdapter.NetworkReport.AvailableNetworks)
  40. {
  41. AvailableNetworksComboBox.Items.Add(network.Ssid);
  42. }
  43. }
  44. private async void ConnectButton_Click(object sender, RoutedEventArgs e)
  45. {
  46. var selectedSsid = AvailableNetworksComboBox.SelectedItem as string;
  47. if (selectedSsid == null)
  48. {
  49. await new MessageDialog("Bitte wählen Sie ein WLAN-Netzwerk aus der Liste aus").ShowAsync();
  50. return;
  51. }
  52. var selectedNetwork = _wifiAdapter.NetworkReport.AvailableNetworks.FirstOrDefault(network => network.Ssid == selectedSsid);
  53. if (selectedNetwork == null)
  54. {
  55. await new MessageDialog("Das ausgewählte Netzwerk wurde nicht gefunden").ShowAsync();
  56. return;
  57. }
  58. string password = PasswordTextBox.Text;
  59. WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Automatic;
  60. var credential = new PasswordCredential { Password = password };
  61. var connectionResult = await _wifiAdapter.ConnectAsync(selectedNetwork, reconnectionKind, credential);
  62. if (connectionResult.ConnectionStatus == WiFiConnectionStatus.Success)
  63. {
  64. await new MessageDialog("Erfolgreich mit dem Netzwerk verbunden").ShowAsync();
  65. }
  66. else
  67. {
  68. await new MessageDialog($"Verbindungsfehler: {connectionResult.ConnectionStatus}").ShowAsync();
  69. }
  70. }
  71. }
  72. }

WPF启动程序:
主窗口.xaml.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.Diagnostics;
  16. namespace UWPStartTest
  17. {
  18. /// <summary>
  19. /// Interaction logic for MainWindow.xaml
  20. /// </summary>
  21. public partial class MainWindow : Window
  22. {
  23. public MainWindow()
  24. {
  25. InitializeComponent();
  26. }
  27. private void Button_Click(object sender, RoutedEventArgs e)
  28. {
  29. Process.Start("myapp://");
  30. }
  31. }
  32. }
  33. //NUGET Microsoft.Toolkit.Wpf.UI.XamlHost wird benltigt!!!
  34. //NUGET Microsoft.Windows.SDK.Contracts für die passende WIN 10 Version
  35. //.NET 4.8 oder höher

主窗口.xaml

  1. <Window x:Class="UWPStartTest.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:xamlhost="clr-namespace:Microsoft.Toolkit.Wpf.UI.XamlHost;assembly=Microsoft.Toolkit.Wpf.UI.XamlHost"
  7. mc:Ignorable="d"
  8. Title="MainWindow" Height="450" Width="800">
  9. <Grid>
  10. <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
  11. </Grid>
  12. </Window>

uoifb46i

uoifb46i1#

您可以使用Protocol在WPF中启动UWP。
1.在UWP项目的文件Package.appxmanifest中定义协议名称。

  1. <Extensions>
  2. <uap:Extension Category="windows.protocol">
  3. <uap:Protocol Name="uwptestapp">
  4. <uap:DisplayName>UWP-Test-app</uap:DisplayName>
  5. </uap:Protocol>
  6. </uap:Extension>
  7. </Extensions>

字符串
1.覆盖App.xaml.cs中的Application.OnActivated。

  1. protected override void OnActivated(IActivatedEventArgs args)
  2. {
  3. Frame rootFrame = Window.Current.Content as Frame;
  4. if (rootFrame == null)
  5. {
  6. rootFrame = new Frame();
  7. Window.Current.Content = rootFrame;
  8. }
  9. rootFrame.Navigate(typeof(MainPage));
  10. Window.Current.Activate();
  11. }


1.使用LaunchUriAsync和协议名称在WPF中启动UWP。

  1. using Windows.System;
  2. private async void Button_Click(object sender, RoutedEventArgs e)
  3. {
  4. var res=await Launcher.LaunchUriAsync(new Uri("uwptestapp:"));
  5. }


注意:要在桌面应用中调用Windows运行时API,您需要修改目标Framework。
右键单击您的WPF项目->选择Unload Project->修改TargetFramework

  1. <Project Sdk="Microsoft.NET.Sdk">
  2. <PropertyGroup>
  3. <OutputType>WinExe</OutputType>
  4. <TargetFramework>net6.0-windows10.0.22621.0</TargetFramework>
  5. <Nullable>enable</Nullable>
  6. <UseWPF>true</UseWPF>
  7. <SupportedOSPlatformVersion>10.0.22621.0</SupportedOSPlatformVersion>
  8. </PropertyGroup>
  9. </Project>

展开查看全部

相关问题