How do I write to command line from a WPF application? How do I write to command line from a WPF application? wpf wpf

How do I write to command line from a WPF application?


This is actually trivial:

public void WriteToConsole(string message){  AttachConsole(-1);  Console.WriteLine(message);}[DllImport("Kernel32.dll")]public static extern bool AttachConsole(int processId);

This method will write your message to the console if your program was started from the command line, otherwise it will do nothing.

If you want to use an alternative output mechanism when you weren't started from the command line you can do it this way:

public void WriteToConsole(string message){  _connected = _connected || AttachConsole(-1);  if(_connected)    Console.WriteLine("Hello");  else    ... other way to output message ...}bool _connected;[DllImport("Kernel32.dll")]public static extern bool AttachConsole(int processId);


The full code for this particular task is:

    public static void WriteToConsole(string message)    {        AttachConsole(-1);        System.Console.WriteLine(message);        SendKeys.SendWait("{ENTER}");        FreeConsole();    }    [DllImport("Kernel32.dll")]    private static extern bool AttachConsole(int processId);    [DllImport("kernel32.dll")]    private static extern bool FreeConsole();

All credits goes to Ray Burns & Scott Marlowe.


Set the project type to "Console Application" instead of "Windows Application". This will cause the Application to attach to the console from which it was launched (or create a console if there was not one already).