1

I am trying to make a WPF application that can also be run from the command line. I have a WPF app that that I am able to achieve this to some extent with. It is possible to run with 0 arguments and a window will load.

When I run it with > 0 arguments the idea is to have it run from the command line and thus should print to the command line. So for this I have Attached a console and then Freed the console after I am done.

However the following results on the command line when everything is finished.

I am able to run another command here but why isn't it displaying the full directory to make it clear that it has finished?

Is there anyway this can be resolved?

Command line output

On further inspection I have noticed that it seems to be printing the new line before the output rather than after.

enter image description here

public partial class App : Application
{
    [DllImport("Kernel32.dll")]
    public static extern bool AttachConsole(int processId);

    [DllImport("Kernel32.dll")]
    private static extern bool FreeConsole();

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        if (e.Args.Length > 0)
        {
            AttachConsole(-1);
            Console.WriteLine("\nStart");
            Console.WriteLine("Stop");
            Console.WriteLine("");
            FreeConsole();
        }
        else
        {
            new MainWindow().ShowDialog();
        }
        this.Shutdown();
    }
}
Community
  • 1
  • 1
Dan Smith
  • 280
  • 3
  • 13

2 Answers2

0

Have you tried using the AllocConsole function? I have always used it without any problem.

[DllImport("Kernel32")]
internal static extern bool AllocConsole();
ForeverZer0
  • 2,379
  • 1
  • 24
  • 32
  • So I have tried replacing the AttachConsole(-1) with AllocConsole() and the result is nothing it printed to the console. – Dan Smith Aug 20 '14 at 22:48
0

Looks like you can't do it that way. What you need are 2 versions:

  • app.exe
  • app.com

if launched from the command line with command app then the .com will be preferentially executed. This is a console app and if the input suggests that really the GUI should be launched then it launches the exe. Otherwise it continues as a console app and does whatever it needs to.

See: https://learn.microsoft.com/en-us/archive/blogs/junfeng/how-to-make-an-application-as-both-gui-and-console-application

This is what devenv does.

Pete
  • 4,784
  • 26
  • 33