我有一個 WPF 桌面應用程式,它是使用 Windows 應用程式包 (WAP) 專案進行 MSIX 打包的。我已經知道如何在第一次使用 URI 激活時通過呼叫AppInstance.GetActivatedEventArgs()然后分析引數來啟動我的 WPF 桌面應用程式:
if (activatedEventArgs.Kind == ActivationKind.Launch)
{
if (((LaunchActivatedEventArgs)activatedEventArgs).Arguments == "myactivationcode")
// .. do something
}
但是,如果用戶第二次運行 URI 激活,而我的應用程式已經啟動,我了解到我的應用程式的新實體已啟動。UWP 應用不會發生這種情況,只有桌面應用才會發生這種情況。我可以殺死第二個實體以遵循所需的單例模式,但我想要的是我的 WPF 應用程式的第一個實體獲得一些事件,讓它知道回到視圖中。
我研究過的東西沒有我能看到的答案:
- 如何在 Windows 應用程式打包專案中處理 URI 激活?
- 如何從作為 UWP 運行的 WPF 應用程式處理檔案激活?
- https://docs.microsoft.com/en-us/windows/uwp/launch-resume/handle-uri-activation#step-3-handle-the-activated-event
是否存在用于 URI 重新激活的任何此類 API 或事件?或者我是否需要在我的應用程式的第二個實體上執行其他形式的 IPC,例如命名管道或 WCF?在這里的任何幫助將不勝感激。
uj5u.com熱心網友回復:
但是,如果用戶第二次運行 URI 激活,而我的應用程式已經啟動,我了解到我的應用程式的新實體已啟動。
是否啟動第二個實體取決于您的自定義Main方法的實作。
在您的第二個鏈接中,有一個指向博客文章的鏈接和一個演示如何防止啟動另一個實體的代碼示例。
它使用命名管道與已經運行的應用程式實體進行通信,并將序列化傳遞IActivatedEventArgs給它:
[STAThread]
static void Main(string[] args)
{
IActivatedEventArgs activatedEventArgs = AppInstance.GetActivatedEventArgs();
using (Mutex mutex = new Mutex(false, AppUniqueGuid))
{
if (mutex.WaitOne(0, false))
{
new Thread(CreateNamedPipeServer) { IsBackground = true }
.Start();
s_application = new App();
s_application.InitializeComponent();
if (activatedEventArgs != null)
s_application.OnProtocolActivated(activatedEventArgs);
s_application.Run();
}
else if (activatedEventArgs != null)
{
//instance already running
using (NamedPipeClientStream namedPipeClientStream
= new NamedPipeClientStream(NamedPipeServerName, AppUniqueGuid, PipeDirection.Out))
{
try
{
namedPipeClientStream.Connect(s_connectionTimeout);
SerializableActivatedEventArgs serializableActivatedEventArgs = Serializer.Serialize(activatedEventArgs);
s_formatter.Serialize(namedPipeClientStream, serializableActivatedEventArgs);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, string.Empty, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
}
是否存在用于 URI 重新激活的任何此類 API 或事件?
不
或者我是否需要在我的應用程式的第二個實體上執行其他形式的 IPC,例如命名管道或 WCF?
是的。同樣,請參閱上述博客文章和隨附的代碼示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461824.html
