c# - 两个应用程序实例之间的简单通信

标签 c# communication single-instance

我有一个 WPF 应用程序,可以采用一些可选的命令行参数。

此应用程序也是一个单实例应用程序(如果实例已打开,则使用互斥体关闭任何实例)。

我想要它做的是,如果某些东西尝试使用某些命令行参数打开应用程序,则应用程序将执行它应该对这些参数执行的操作(在我的应用程序中,它会根据 cmd 打开不同的对话框)线)。

实现这一目标的最简单方法是什么?

在伪代码中,这就是我正在寻找的内容

protected override void OnStartup(StartupEventArgs e)
{
     bool mutexIsNew;
     using (System.Threading.Mutex m = 
            new System.Threading.Mutex(true, "MyApplication", out mutexIsNew))
     {
         //if this is not the first instance of the app
         if (!mutexIsNew)
         {
              //if there is some cmd line args  
              if (e.Args.Length > 0)
              {
                   //send the args to the older instance so it can handle them
                   SendToOtherInstance(e.Args);
                   //shutdown this new instance
                   Application.Current.Shutdown();
               }

         }
     }
     base.OnStartup(e);
}

最佳答案

Code Project 上有很多单实例应用的实现,实际上有很多,很难决定你想要哪一个......

我尝试了几种解决方案,我真的很喜欢 this one 。它使得拦截传递给第二个实例的命令行参数变得非常容易。

关于c# - 两个应用程序实例之间的简单通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4541354/

相关文章:

c++ - Silverlight 客户端可以与 C++ 服务器通信吗?

vim - 让 gVim 始终运行单个实例

c# - 为什么我不能等待异步方法?

c++ - 从另一个类调用一个类方法

Controller 之间的javafx通信

Java在设置组件大小时重用Dimension对象

android - 任务的根android Activity

c# - Sharepoint Online 无法使用 CSOM 创建 DocumentSet Microsoft.SharePoint.Client.DocumentManagement.dll

c# - Windows Phone 8 (C#) 上 NSUserDefaults 的等价物是什么

c# - 为什么 HttpClient.PostAsync 在 WPF 环境中返回失败?