4

I have a C++ MFC program that works, but I would also like to be able to invoke a simpler version through the command line. (This works by using a cmd line version if there are cmd line arguments.) I would like the program to use the current "cmd" window that is open to run, and create a new shell for it to some degree. In InitInstance(), I have...

CString cmdLine;
cmdLine.Format("%s", this->m_lpCmdLine);
if(cmdLine.IsEmpty())
    dlg.DoModal(); // Run application normally
else
{
    CString header = "Welcome to the program!";
    AttachConsole(ATTACH_PARENT_PROCESS);     // Use current console window
    LPDWORD charsWritten = 0;
    WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), header, header.GetLength(), NULL, NULL);
}

How do I go about getting input into my program? cin seems not to work. I tried something like this:

char input[10] = "";
while((strcmp(input, "q") != 0) && (strcmp(input, "quit") != 0))
    scanf("%s", input);

But it doesn't seem to work, as the command window waits for a new prompt.

1 Answers1

4

The fundamental problem is that your MFC program is not marked as a console mode program in its EXE header. So the command processor has no reason to wait for it to complete, like it normally does for console mode programs. You now have two programs trying to read from the console, you and cmd.exe. You lose.

There are several workarounds, all unattractive:

  • Start your program with start /wait yourapp.exe arg1 arg2...
  • Change the Linker + System + SubSystem setting to Console. Call FreeConsole when you find out that you don't have any arguments. The flash is kinda nasty, well known to Java programmers
  • Call AllocConsole() when you find out you do have arguments. You'll get your own console.
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • * Call `AttachConsole(ATTACH_PARENT_PROCESS)` first, and if that fails call `AllocConsole`. You'll get your own console only when necessary (e.g. when called from Explorer.EXE). – MSalters Oct 18 '12 at 12:11
  • No, that ignores the problem the OP is trying to solve, two programs trying to read from the console at the same time. – Hans Passant Oct 18 '12 at 12:28
  • freopen("CON", "w", stdout); freopen("CON", "r", stdin); works the best – user1754508 Nov 05 '12 at 20:25