2010-05-21 242 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文檔。

相關問題