1

I'd like to create a tool that can either act as command line (display some console output based on input parameters), or display a window, based on input parameters.

I'm using MSV2012 with C++, and it seems you have to 'choose' between console and window app.

I know the net is filled with samples which use AllocConsole() and redirect std::out, but it doesn't make it feel like a command line application : calling the exe from the windows console will open a new window with the console output...

Is there a way to have it use the current console window instead of allocating a new one?

If not possible, I'll make 2 applications instead, but that's a pity..

Mikarnage
  • 893
  • 1
  • 9
  • 24
  • 2
    This is very old article, but it provides one possible solution: http://www.codeguru.com/cpp/w-d/console/redirection/article.php/c3955/Using-the-Console-Like-MSDEV.htm – Alex F Dec 16 '12 at 09:32
  • +1 on what Alex just linked. Visual Studio accomplishes the same thing from the command line you asking about. – selbie Dec 16 '12 at 09:58
  • Possible duplicate: http://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-app – Harry Johnston Dec 17 '12 at 02:32
  • The quick answer is that you can use AttachConsole instead of AllocConsole, but there are downsides, and having two applications is usually the best approach. See the answers to the linked question for more details. – Harry Johnston Dec 17 '12 at 02:34
  • It's not technically supported but I found a good solution by getting a snapshot for the current process, finding the parent process, attaching to it's console if it's a console app or creating one with AllocConsole, redirecting the output, getting the thread of the parent process if it's cmd.exe and suspending it, resuming it just before I exit my app – user9778277 May 11 '18 at 19:41

2 Answers2

1

Someone else may have a more authoritative answer, but I don't believe it's supported.

The usual workaround is to create a Windows app, but have a command-line wrapper that launches it from the CLI (and provides a channel for communicating with the original console).

JasonD
  • 16,464
  • 2
  • 29
  • 44
0

It's not technically supported but I found a good solution by getting a snapshot for the current process, finding the parent process, attaching to it's console if it's a console app or creating one with AllocConsole, redirecting the output, getting the thread of the parent process if it's cmd.exe and suspending it, resuming it just before I exit my app

user9778277
  • 153
  • 1
  • 11