2010-05-21 239 views
1

如何从非控制台.NET应用程序内打开控制台窗口(因此我在调试时有System.Console.Out和朋友的位置)?如果是纯粹为了调试,使用Debug class并在Visual Studio发送一切调试输出窗口从非控制台.NET应用程序内创建控制台

/* 
    EnsureConsoleExists() will create a console 
    window and attach stdout (and friends) to it. 

    Can be useful when debugging. 
*/ 

FILE* const CreateConsoleStream(const DWORD stdHandle, const char* const mode) 
{ 
    const HANDLE outputHandle = ::GetStdHandle(stdHandle); 
    assert(outputHandle != 0); 
    const int outputFileDescriptor = _open_osfhandle(reinterpret_cast<intptr_t>(outputHandle), _O_TEXT); 
    assert(outputFileDescriptor != -1); 
    FILE* const outputStream = _fdopen(outputFileDescriptor, mode); 
    assert(outputStream != 0); 
    return outputStream; 
} 

void EnsureConsoleExists() 
{ 
    const bool haveCreatedConsole = (::AllocConsole() != 0); 
    if (haveCreatedConsole) { 
     /* 
      If we didn't manage to create the console then chances are 
      that stdout is already going to a console window. 
     */ 
     *stderr = *CreateConsoleStream(STD_ERROR_HANDLE, "w"); 
     *stdout = *CreateConsoleStream(STD_OUTPUT_HANDLE, "w"); 
     *stdin = *CreateConsoleStream(STD_INPUT_HANDLE, "r"); 
     std::ios::sync_with_stdio(false); 

     const HANDLE consoleHandle = ::GetStdHandle(STD_OUTPUT_HANDLE); 
     assert(consoleHandle != NULL && consoleHandle != INVALID_HANDLE_VALUE); 

     CONSOLE_SCREEN_BUFFER_INFO info; 
     BOOL result = ::GetConsoleScreenBufferInfo(consoleHandle, &info); 
     assert(result != 0); 

     COORD size; 
     size.X = info.dwSize.X; 
     size.Y = 30000; 
     result = ::SetConsoleScreenBufferSize(consoleHandle, size); 
     assert(result != 0); 
    } 
} 

回答

2


在C++中可以使用各种Win32 API的实现。

1

您可以使用AttachConsole如下所述:

http://www.pinvoke.net/default.aspx/kernel32.attachconsole

但奥斯汀说,如果你在调试器调试我建议使用Debug类代替。

+0

这看起来很有希望,但是它创建的控制台窗口并未附加到'System.Console.Out'。 – pauldoo 2010-05-21 14:38:11

+0

我不知道如何链接那些我无所事事的人。有'AllocConsole'方法,但我认为你会遇到同样的问题。 – 2010-05-21 14:59:19

2

你会想P/Invoke AllocConsole()。请务必在之前使用任何控制台方法尽早完成,。在pinvoke.net上查找声明

获取控制台的一种非常快捷的方式:Project + Properties,Application选项卡,Output type = Console Application。

对于更持久的提供诊断输出的方法,您确实需要使用Trace类。它非常灵活,您可以使用app.exe.config文件来确定跟踪输出的位置。查看TraceListener类的MSDN Library文档。

相关问题