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.
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 /wait yourapp.exe arg1 arg2...