更好的选择是使用应用服务。
应用服务可以让您在两个应用程序之间来回通信。幸运的是,有一个用于桌面应用程序的 UWP 扩展,可以帮助您在 win32 项目中使用应用程序服务。步骤如下。
1.在你的 Win32 应用中安装 UwpDesktop
Install-Package UwpDesktop
2。在您的 Win32 应用中创建应用服务终结点
private async void btnConfirm_Click(object sender, EventArgs e)
{
AppServiceConnection connection = new AppServiceConnection();
connection.AppServiceName = "CommunicationService";
connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
var result = await connection.OpenAsync();
if (result == AppServiceConnectionStatus.Success)
{
ValueSet valueSet = new ValueSet();
valueSet.Add("name", txtName.Text);
var response = await connection.SendMessageAsync(valueSet);
if (response.Status == AppServiceResponseStatus.Success)
{
string responseMessage = response.Message["response"].ToString();
if (responseMessage == "success")
{
this.Hide();
}
}
}
}
如果您的 .exe 文件是 UWP 项目的一部分,您的 Package.Current.Id.FamilyName 应重定向到 UWP 的 PFN。
3.在 UWP 应用中创建频道的另一端
现在在你的 UWP 应用中创建一个基本的应用服务
AppServiceConnection connection = new AppServiceConnection();
connection.AppServiceName = "CommunicationService";
connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
connection.RequestReceived += Connection_RequestReceived;
var result = await connection.OpenAsync();
4.处理连接请求
最后,你需要处理Connection_RequestReceived中的传入连接
private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var deferral = args.GetDeferral();
string name = args.Request.Message["name"].ToString();
Result.Text = $"Hello {name}";
ValueSet valueSet = new ValueSet();
valueSet.Add("response", "success");
await args.Request.SendResponseAsync(valueSet);
deferral.Complete();
}
虽然我们只返回valueSet 中的一项,但您可以在valueSet 中包含其他项,例如特定指令或参数。这些将在 Win32 端提供给您。
这是一个非常简单的示例,由 Centennial 团队在官方 MSDN 博客文章中按比例缩小,可在此处找到:
https://blogs.msdn.microsoft.com/appconsult/2016/12/19/desktop-bridge-the-migrate-phase-invoking-a-win32-process-from-a-uwp-app/
为了使其更健壮,您可以确保仅在您的 Win32 应用程序启动后在 UWP 端创建应用服务连接,方法是使用博文中的AppServiceTriggerDetails
您还需要在 Package.appxmanifest 文件中声明应用服务
<Extensions>
<uap:Extension Category="windows.appService">
<uap:AppService Name="CommunicationService" />
</uap:Extension>
<desktop:Extension Category="windows.fullTrustProcess" Executable="Migrate.WindowsForms.exe" />
</Extensions>
您可以在此处从博客文章中找到示例:
https://github.com/qmatteoq/DesktopBridge/tree/master/6.%20Migrate
快乐编码。 :)