简体   繁体   中英

WPF display command line options

I need to add command line options to my WPF project, what I currently have sort of works but its not very nice. I need a more professional looking solution.

To write start and stop i do the following:

AttachConsole(-1);
Console.WriteLine("Start");
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Stop");

Which produces the output:

C:\Work>TestWriteCLI.exe -h

C:\Work>Start
Stop

There are several things wrong with this:

  1. After i run the exe a new line is created with C:\\Work> in it, I don't want this, i want it to print "Start" directly to the console.
  2. After "Stop" is displayed, the program just waits there, waiting for "Enter" to be pressed, I don't want that either, i just want it to exit.

This is the output I am trying to achieve:

C:\Work>TestWriteCLI.exe -h
Start
Stop
C:\Work>

Other similar questions here have provided solutions I don't like, for example, I don't want to be creating new console windows. I have a console, i want it to run it that console not open a new one, display things, then close it and be back in my original console.

I also don't want to change my project to be a command line project.

My project is a WPF project, it should handle command line options in the normal way a command line project can, using WPF methods if possible.

Your help in this is greatly appreciated.

Many thanks

You should use AllocConsole() from Kernel32 assembly and to close console you can use FreeConsole() .

Import methods in your class

[DllImport("Kernel32")]
public static extern void AllocConsole();

[DllImport("Kernel32")]
public static extern void FreeConsole();

and use them this way -

AllocConsole();
Console.WriteLine("Start");
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Stop");
FreeConsole();

For your first problem, just run the executable with the start command with /W or /Wait as option, as documented here :

C:\Work>start /W TestWriteCLI.exe -h

For the second problem, add following line at the end of your code:

    System.Windows.Forms.SendKeys.SendWait("{ENTER}"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM