能否从UWP向Win32端发起AppServices连接?
UWP向Win32发起App Services连接的支持说明
结论
从Windows 10 1809(内部版本号17763)开始,完全支持UWP应用向同设备运行的Win32进程发起App Services连接,连接建立后的消息交互逻辑和Win32主动连接UWP的场景完全一致。
前置要求
- 通用兼容方案(支持Win10 1809及以上版本)需要将Win32进程和发起请求的UWP应用打包在同一个MSIX包中,两者共享同一个应用身份上下文
- 需要在应用包的清单文件中声明App Service信息,其中
Name字段的值需要和UWP端连接时填入的服务名称完全匹配 - 两端进程必须运行在同一个用户会话下,暂不支持跨用户发起连接
核心实现示例
UWP端(C# 发起连接)
using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; // 构造连接对象 AppServiceConnection serviceConnection = new AppServiceConnection(); // 填入你在包清单中声明的App Service名称 serviceConnection.AppServiceName = "com.example.myapp.customservice"; // 填入当前应用的包家族名,可通过Package.Current.Id.FamilyName直接获取 serviceConnection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; // 发起连接 AppServiceConnectionStatus connectStatus = await serviceConnection.OpenAsync(); if (connectStatus == AppServiceConnectionStatus.Success) { // 连接成功后发送测试消息 ValueSet requestMsg = new ValueSet(); requestMsg.Add("action", "get_data"); AppServiceResponse response = await serviceConnection.SendMessageAsync(requestMsg); if (response.Status == AppServiceResponseStatus.Success) { var result = response.Message["result"]; // 处理Win32返回的响应数据 } }
Win32端(C++/WinRT 作为服务端响应)
#include <winrt/Windows.ApplicationModel.AppService.h> #include <winrt/Windows.Foundation.Collections.h> using namespace winrt::Windows::ApplicationModel::AppService; using namespace winrt::Windows::Foundation::Collections; // 接收App Service激活事件时初始化连接 void OnAppServiceActivated(AppServiceActivatedEventArgs const& args) { AppServiceConnection connection = args.Connection(); // 监听UWP端发来的消息 connection.RequestReceived([](AppServiceConnection const&, AppServiceRequestReceivedEventArgs const& args) { ValueSet requestData = args.Request().Message(); // 处理UWP发送的请求 auto action = requestData.TryLookup(L"action").try_as<hstring>(); ValueSet responseData; if (action == L"get_data") { responseData.Insert(L"result", L"test_data_from_win32"); } // 返回响应给UWP args.Request().SendResponseAsync(responseData); }); }
内容的提问来源于stack exchange,提问作者Enric Casals
相关产品推荐
相关产品推荐

