How do I write to the CommandPrompt from Windows G

2019-07-12 20:17发布

问题:

Operating Environment: Windows 7, Visual Studio 2010, CLR GUI.

So I've been given the unglorious task of enhancing a GUI application that is started from a command prompt. Because it is. Because poor design decisions by previous implementers. Anyway, it launches one of several GUIs depending upon the input arguments.

I'd like to be able to print back to the same command prompt window if (when) the user types something that the code doesn't understand.

Here's what I've tried (none of which output anything):

int main( array<System::String^>^ args )
{
  Application::EnableVisualStyles();
  Application::SetCompatibleTextRenderingDefault(false);

  OutputDebugString("hello");
  Trace::WriteLine("hello");
  Debug::Trace::WriteLine("hello");
  Console::WriteLine("hello");
  std::cout << "hello";
  printf("hello");
  return 0;
}

Thanks in advance!

Update: I don't want to use AllocConsole(), as that opens a new console that disappears along with all of the data when the application exits. Similarly, a pop-up message box won't work. I'm looking for a way to make the output persistent.

The only way I can get output from the application to date is via a message box (non-persistent) or opening a new console that disappears when the application exits (via AllocConsole() ). And I'm running from a command prompt, not the debugger's "Play" button.

Update Why the down-vote for not doing research? I spent a day trying to solve this, looking through dozens of posts trying to find a solution, and to date I've found others looking for the same answer, but not finding it. AllocConsole() or changing the project type is always the solution, but neither is a solution for me.

Update I added the "full code", which is the 2 statements. THAT IS ALL THE CODE. So simple. I'm skipping the start of the GUI because I don't care about that right now, I just want it to print back to the console where the application was started. The most basic HelloWorld. If there are project settings I need to post, I don't know which ones would be relevant. This is where I want to print to the console, before the GUI is ever up. I can't show the GUI if there is an error in the user input.

回答1:

Right click on the project, select Properties
Under Linker -> System, Change Subsystem from Windows to Console.

A Windows subsystem application cannot write to console, but by changing the subsystem to Console (which can write to the calling console), the Form part of the application can still work (tested in Visual Studio 2010).