更好的選擇是使用應用服務。
應用程序服務可以允許您在兩個應用程序之間來回通信。幸運的是,桌面應用程序存在UWP擴展,它可以幫助您在win32項目中使用應用程序服務。以下是步驟。
1.在您的Win32應用程序
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文件的一部分安裝UwpDesktop 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端提供給您。
這是一個非常簡單的例子,從百年隊MSDN官方博客中縮減這裏找到:
https://blogs.msdn.microsoft.com/appconsult/2016/12/19/desktop-bridge-the-migrate-phase-invoking-a-win32-process-from-a-uwp-app/
爲了使其更加堅固,你可以確保你創建在UWP端應用服務連接只有當您的Win32應用程序使用AppServiceTriggerDetails
時,纔會在博客文章中使用
您還需要在包中聲明應用程序服務。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
編碼愉快。 :)
被接受爲答案,因爲它專注於我的問題。 – GIANGPZO