我有一个 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/