C# 如何将参数从cmd获取到正在运行的WPF应用程序中
我有一个WPF应用程序,可以通过命令行获取参数。我的应用程序不能重复(我将其设置为单个实例),但我希望能够多次添加参数,并在不打开另一个窗口的情况下将其添加到runnig应用程序中。 现在在我的代码中,我检查应用程序是否有另一个实例——如果有,我抛出一个异常。 我正在寻找一种能够多次运行以下脚本的方法:C# 如何将参数从cmd获取到正在运行的WPF应用程序中,c#,wpf,cmd,parameter-passing,C#,Wpf,Cmd,Parameter Passing,我有一个WPF应用程序,可以通过命令行获取参数。我的应用程序不能重复(我将其设置为单个实例),但我希望能够多次添加参数,并在不打开另一个窗口的情况下将其添加到runnig应用程序中。 现在在我的代码中,我检查应用程序是否有另一个实例——如果有,我抛出一个异常。 我正在寻找一种能够多次运行以下脚本的方法: Myapp.exe -firstname first -lastname last 每次运行的应用程序都会将插入的参数添加到其列表中。 我该怎么做呢?您可以覆盖应用程序类的启动方法。请看一看。
Myapp.exe -firstname first -lastname last
每次运行的应用程序都会将插入的参数添加到其列表中。
我该怎么做呢?您可以覆盖
应用程序
类的启动
方法。请看一看。您将在方法的参数中找到命令行参数。请看一看
因为您需要一些进程间通信机制,所以您可能应该阅读本文。我认为创建WCF服务是最好的选择。在检查应用程序是否为单一应用程序时(如果存在应用程序实例(重复调用)),应用程序应该向用户发送错误消息。在这种情况下,您应该检查是否有命令行参数,如果有,只需发送Close()并返回命令,而不显示任何错误消息。应用程序将从命令行获取参数,并按照它知道的方式处理这些参数。您可以使用application.Current.Shutdown()停止应用程序。如果在OnStartup中调用,则可以在显示的窗口之前追加此项 对于读取参数,可以在OnStartup或Environment.GetCommandLineArgs()中随处使用e.Args
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// check if it is the first instance or not
// do logic
// get arguments
var cmdLineArgs = e.Args;
if (thisisnotthefirst)
{
// logic interprocess
// do logic
// exit this instance
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
// may be some release needed for your single instance check
base.OnExit(e);
}
}
我不知道如何检查单个实例,但我使用互斥体:
protected override void OnStartup(StartupEventArgs e)
{
Boolean createdNew;
this.instanceMutex = new Mutex(true, "MySingleApplication", out createdNew);
if (!createdNew)
{
this.instanceMutex = null;
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
if (this.instanceMutex != null)
{
this.instanceMutex.ReleaseMutex();
}
base.OnExit(e);
}
这将对您有所帮助。但是我的MainWindow类(运行应用程序的类)不能从应用程序继承。Ôo没错,但WPF应用程序的入口点不是
MainWindow
。它是App
类,通常可以在App.xaml和App.xaml.cs中找到,您可以在其中实现覆盖。剩下的应该很简单。我有办法从OnStartApp方法退出应用程序吗?根据yes,应用程序继续运行MainWindow()构造函数;o) 当我使用它时——如果我指向我的主窗口xaml——另一个窗口是打开的。但我想将作为参数获得的详细信息添加到当前正在运行的窗口中。
protected override void OnStartup(StartupEventArgs e)
{
Boolean createdNew;
this.instanceMutex = new Mutex(true, "MySingleApplication", out createdNew);
if (!createdNew)
{
this.instanceMutex = null;
Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
protected override void OnExit(ExitEventArgs e)
{
if (this.instanceMutex != null)
{
this.instanceMutex.ReleaseMutex();
}
base.OnExit(e);
}