2个应用程序实例之间的简单通信 [英] Simple Communication between 2 instances of application

查看:143
本文介绍了2个应用程序实例之间的简单通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

此应用程序也是单实例应用程序(如果已经打开实例,则使用互斥锁关闭任何实例).

我想做的是,如果某些东西试图用一些cmd行的args打开应用程序,则该应用程序将执行与这些操作相同的操作(在我的应用程序中,它将基于cmd打开不同的对话框行).

最简单的方法是什么?

在psedo代码中,这就是我正在寻找的

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上有很多单实例应用程序的实现,实际上有很多这样的实现,很难决定要使用哪个实例...

我尝试了几种解决方案,我真的很喜欢这一个.这样可以很容易地拦截传递给第二个实例的命令行参数.

I have a WPF application that can take a few optional command line arguments.

This application is also a single instance application (using a mutex to close any instances if one is already open).

What I want for it to do though, is if something tries to open the application with some cmd line args, that the application will do what it's suppose to do with those (in my application it opens different dialogs based on the cmd line).

What is the easiest way to achieve this?

In psedo code here is what i'm looking for

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);
}

解决方案

There are lots of implementations of single instance apps on Code Project, actually there are so many of them it's hard to decide which one you want...

I tried several solutions, and I really like this one. It makes it very easy to intercept command line parameters passed to the second instance.

这篇关于2个应用程序实例之间的简单通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆