如何从UWP应用中关闭FullTrustProcess进程?
解决UWP与FullTrustProcess互斥运行问题
问题场景
关闭UWP应用时会启动FullTrustProcess(系统托盘进程),托盘右键打开UWP时会自动关闭自身;但双击桌面UWP图标重新启动时,原FullTrustProcess仍在后台运行,导致两者同时存在。需要实现互斥逻辑,确保同一时间仅UWP或FullTrustProcess中的一方处于运行状态。
现有核心代码:
UWP关闭触发FullTrustProcess启动(MainPage.xaml.cs)
private async void HandleSystemNavigationManagerCloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e) { if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) { await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } }
托盘进程唤起UWP并自关闭
private async void OpenUWPApp(object sender, EventArgs e) { var appListEntries = await Package.Current.GetAppListEntriesAsync(); await appListEntries.First().LaunchAsync(); Application.Exit(); }
UWP的AppService连接逻辑(App.xaml.cs)
public static AppServiceConnection Connection = null; protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(args); if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails details) { AppServiceDeferral = args.TaskInstance.GetDeferral(); args.TaskInstance.Canceled += OnTaskCanceled; Connection = details.AppServiceConnection; Connection.RequestReceived += HandleSystemTrayConnectionRequestReceived; Connection.ServiceClosed += HandleSystemTrayConnectionServiceClosed; } }
曾尝试通过AppServiceConnection通讯,但新UWP会话启动时Connection为null,无法直接发送关闭指令。
解决方案
方案1:通过进程名检测并终止FullTrustProcess
利用P/Invoke调用Win32 API,在UWP启动时检测指定进程并终止:
- 添加P/Invoke工具类:
using System; using System.Runtime.InteropServices; using System.Linq; using Windows.System; public static class ProcessHelper { [DllImport("kernel32.dll", SetLastError = true)] private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hObject); private const uint PROCESS_TERMINATE = 0x0001; public static async void KillFullTrustProcess(string processName) { var processes = await ProcessManager.GetProcessesAsync(); var targetProcess = processes.FirstOrDefault(p => p.ExecutableFileName.Equals(processName, StringComparison.OrdinalIgnoreCase)); if (targetProcess != null) { IntPtr hProcess = OpenProcess(PROCESS_TERMINATE, false, (uint)targetProcess.Id); if (hProcess != IntPtr.Zero) { TerminateProcess(hProcess, 0); CloseHandle(hProcess); } } } }
- 在UWP的
OnLaunched事件中调用:
protected override async void OnLaunched(LaunchActivatedEventArgs e) { base.OnLaunched(e); // 替换为你的FullTrustProcess可执行文件名,如"YourDesktopTray.exe" ProcessHelper.KillFullTrustProcess("YourDesktopTray.exe"); // 其他初始化逻辑 }
方案2:命名管道实现双向通讯
在FullTrustProcess中创建命名管道,UWP启动时尝试连接并发送关闭指令:
- FullTrustProcess侧启动管道服务:
using System.IO.Pipes; using System.Threading.Tasks; public class PipeServer { private NamedPipeServerStream _pipeServer; public async void Start() { _pipeServer = new NamedPipeServerStream("UWP_Tray_Pipe", PipeDirection.InOut, 1); await _pipeServer.WaitForConnectionAsync(); using (var reader = new StreamReader(_pipeServer)) { string message = await reader.ReadLineAsync(); if (message == "SHUTDOWN_TRAY") { Application.Exit(); } } } } // 托盘进程启动时初始化管道 protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var pipeServer = new PipeServer(); pipeServer.Start(); // 托盘图标初始化等逻辑 }
- UWP侧发送关闭指令:
using System.IO.Pipes; using System.Threading.Tasks; private async Task SendShutdownCommand() { try { using (var pipeClient = new NamedPipeClientStream(".", "UWP_Tray_Pipe", PipeDirection.InOut)) { await pipeClient.ConnectAsync(1000); using (var writer = new StreamWriter(pipeClient)) { await writer.WriteLineAsync("SHUTDOWN_TRAY"); await writer.FlushAsync(); } } } catch (TimeoutException) { // 连接超时,说明托盘进程未运行 } } protected override async void OnLaunched(LaunchActivatedEventArgs e) { base.OnLaunched(e); await SendShutdownCommand(); // 其他初始化逻辑 }
方案3:改进AppService主动连接逻辑
让FullTrustProcess启动时主动发起AppService连接,UWP启动时通过新连接发送关闭指令:
- FullTrustProcess侧主动连接UWP:
using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; private AppServiceConnection _appServiceConnection; private async Task ConnectToUwp() { _appServiceConnection = new AppServiceConnection(); _appServiceConnection.AppServiceName = "UWP_Tray_AppService"; // 需与UWP清单中声明一致 _appServiceConnection.PackageFamilyName = Package.Current.Id.FamilyName; var status = await _appServiceConnection.OpenAsync(); if (status == AppServiceConnectionStatus.Success) { _appServiceConnection.RequestReceived += (sender, args) => { if (args.Request.Message["Command"].ToString() == "SHUTDOWN") { Application.Exit(); } }; } } // 托盘进程启动时调用 protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); _ = ConnectToUwp(); // 其他初始化逻辑 }
- UWP侧发送关闭指令:
private async Task SendShutdownViaAppService() { var appServiceConnection = new AppServiceConnection(); appServiceConnection.AppServiceName = "UWP_Tray_AppService"; appServiceConnection.PackageFamilyName = Package.Current.Id.FamilyName; var status = await appServiceConnection.OpenAsync(); if (status == AppServiceConnectionStatus.Success) { var message = new ValueSet(); message.Add("Command", "SHUTDOWN"); await appServiceConnection.SendMessageAsync(message); appServiceConnection.Dispose(); } } protected override async void OnLaunched(LaunchActivatedEventArgs e) { base.OnLaunched(e); await SendShutdownViaAppService(); // 其他初始化逻辑 }
参考指南要点
原参考的UWP桌面扩展开发核心内容包括:
- UWP与FullTrustProcess的AppService通讯机制
- UWP关闭唤起桌面进程、桌面进程唤起UWP的生命周期协同逻辑
- 进程间通讯的常用方案(AppService、命名管道、共享内存)
- 实现UWP与桌面进程互斥运行的最佳实践
内容的提问来源于stack exchange,提问作者sme
相关产品推荐
相关产品推荐

