How to create a C ++ MFC program that can be loaded both in GUI mode and through the command line?

I have a C ++ MFC program that works, but I would also like to be able to call a simpler version via the command line. (This works using the version of the cmd line if there are arguments to the cmd line.) I would like the program to use the current "cmd" window that is open to run, and create a new shell for it. 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 access my program? cin doesn't seem to work. I tried something like this:

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

But it does not work because the command window is waiting for a new prompt.

+4
source share
1 answer

The main problem is that your MFC program is not marked as a console program in its EXE header. Thus, the command processor has no reason to wait for its completion, as is usually done for console programs. Now you have two programs that are trying to read from the console, you and cmd.exe. You lose.

There are several workarounds, all unattractive:

  • Run 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 have no arguments. The flash is disgusting, well known to Java programmers.
  • Call AllocConsole () when you find that you have arguments. You will get your console.
+4
source

Source: https://habr.com/ru/post/1440404/


All Articles