如何从cmd获取参数到正在运行的WPF应用程序

时间:2013-03-13 13:10:29

标签: c# wpf cmd parameter-passing

我有一个WPF应用程序,它可以通过命令行获取参数。我的应用程序不能重复(我使它成为单个实例)但我希望能够添加几次参数 - 并将它们添加到runnig应用程序而无需打开另一个窗口。 现在在我的代码中我检查应用程序是否有另一个实例 - 如果是这样我抛出异常。 我正在寻找一种能够运行以下脚本几次的方法:

Myapp.exe -firstname first -lastname last

并且每次运行的应用程序都会将插入的参数添加到其列表中。 我该怎么办?

3 个答案:

答案 0 :(得分:2)

您可以覆盖OnStartup课程的App方法。请看看here。您将在方法的参数中找到命令行参数。请看看here

public class App : Application
{
    protected override OnStartup(StartupEventArgs e)
    {
        var cmdLineArgs = e.Args;
        // your logic here
    }
    // ...
}

由于您需要一些进程间通信机制,因此您可能应该阅读此SO post。我认为创建WCF服务是最好的选择。

答案 1 :(得分:0)

执行检查应用程序是否为单一时 - 如果存在应用程序实例(重复调用) - 应用程序应向用户发送错误消息。在这种情况下,您应该检查是否有命令行参数,如果是 - 只需发送Close()并返回命令而不显示任何错误消息。应用程序将从命令行获取参数,并使用它们知道的操作。

答案 2 :(得分:0)

您可以使用Application.Current.Shutdown()来停止您的应用程序。如果在OnStartup中调用它,则可以在Window显示之前附加。

对于读取参数,您可以在任何地方使用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);
    }
}

我不知道你如何检查单个实例,但我使用Mutex:

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

跳跃会帮助你。