1

I have a WPF application which starts without a window and has a main method as such in the App.xaml.cs,

static void Main(String[] args)

once the application is loaded and running I want to continue to send commandline arguments to it IF POSSIBLE e.g.

myApp.exe "string 1", "string 2"

And get it to react appropriately. Is this possible and if so how or what method should I use the do achieve this?

Rachel 674
  • 69
  • 8
  • 2
    You can't send launch arguments to a running application, because it is - well - running. You could connect to it via a second application that receives the data and sends it to the WPF application. Have a look at the answers given [here](https://stackoverflow.com/questions/1952207/sharing-data-between-two-applications). – Max Play Jul 12 '22 at 21:35
  • Thank you, I was basically wondering if it was possible to do with just one application. I was already looking at memory mapped files. – Rachel 674 Jul 12 '22 at 21:39
  • you sort-of can if but it requires a single-instance app: https://stackoverflow.com/a/19326/1506454 – ASh Jul 12 '22 at 21:59
  • 1
    You could have a second app which is just a command line app and forwards its arguments to the first app, using Named Pipes. – Jim Foye Jul 13 '22 at 00:15
  • You could run the wpf window from a console app. You could then have it read the console input on a separate thread. You would have to manually parse the input. There is no need for two different applications. – Alex Jul 13 '22 at 01:37
  • 2
    So you need to use some IPC method to discover your existing instance and forward an event of some kind to it. eg Try to create a named pipe with a per-user unique name, if you can't then try to connect to it and send your arguments. – Jeremy Lakeman Jul 13 '22 at 01:55
  • Thank you very much for your very helpful comments and suggestions, much appreciated. I am looking at the various options. – Rachel 674 Jul 13 '22 at 16:58

1 Answers1

2

You can start a console window and read the user input.

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    [DllImport("Kernel32")]
    public static extern void AllocConsole();

    protected override void OnStartup(StartupEventArgs e)
    {
        var window = new MainWindow();
        window.Show();
        GetInput();
    }

    private async void GetInput()
    {
        AllocConsole();
        Console.WriteLine("Tell me.");
        while (true)
        {
            var input = await Task.Factory.StartNew(() => Console.ReadLine());
            Console.WriteLine($"You sent : {input}");
        }
    }
}
Alex
  • 710
  • 6
  • 8