简体   繁体   English

如何创建可以在GUI对话模式下或通过命令行启动的C ++ MFC程序?

[英]How to create a C++ MFC program that can boot in both GUI Dialog mode or through the command line?

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. 我有一个C ++ MFC程序,但我也希望能够通过命令行调用更简单的版本。 (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. (如果有cmd行参数,这可以使用cmd行版本。)我希望程序使用当前打开的“cmd”窗口,并在某种程度上为它创建一个新的shell。 In InitInstance(), I have... 在InitInstance()中,我有......

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. cin似乎不起作用。 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. 根本问题是您的MFC程序未在其EXE标头中标记为控制台模式程序。 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. 您现在有两个程序试图从控制台读取,您和cmd.exe。 You lose. 你输了。

There are several workarounds, all unattractive: 有几种解决方法,都没有吸引力:

  • Start your program with start /wait yourapp.exe arg1 arg2... 使用start /wait yourapp.exe arg1 arg2...启动程序start /wait yourapp.exe arg1 arg2...
  • Change the Linker + System + SubSystem setting to Console. 将Linker + System + SubSystem设置更改为Console。 Call FreeConsole when you find out that you don't have any arguments. 当您发现没有任何参数时,请调用FreeConsole。 The flash is kinda nasty, well known to Java programmers 闪存有点讨厌,Java程序员熟知
  • Call AllocConsole() when you find out you do have arguments. 当你发现你确实有参数时调用AllocConsole()。 You'll get your own console. 你会得到自己的控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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