2015-08-24 4 views
5

Я попробовал этот код для вывода на консоль:Вывести на консоль из приложения Win32 GUI на Windows 10

#include <Windows.h> 

#include <stdio.h> 
#include <io.h> 
#include <fcntl.h> 

int APIENTRY WinMain(HINSTANCE hInstance, 
        HINSTANCE hPrevInstance, 
        LPSTR  lpCmdLine, 
        int  nCmdShow) 
{ 
    AllocConsole(); 

    HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE); 
    int hCrt = _open_osfhandle((long) handle_out, _O_TEXT); 
    FILE* hf_out = _fdopen(hCrt, "w"); 
    setvbuf(hf_out, NULL, _IONBF, 1); 
    *stdout = *hf_out; 

    HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE); 
    hCrt = _open_osfhandle((long) handle_in, _O_TEXT); 
    FILE* hf_in = _fdopen(hCrt, "r"); 
    setvbuf(hf_in, NULL, _IONBF, 128); 
    *stdin = *hf_in; 

    printf("Hello!"); 
} 

консоль открывается, но ничего не выводится на него. Что не так с этим кодом?

Я попробовал все эти предложения:

https://justcheckingonall.wordpress.com/2008/08/29/console-window-win32-app/

http://dslweb.nwnexus.com/~ast/dload/guicon.htm

How do I print to the debug output window in a Win32 app?

, но я не мог получить какой-либо вывод на консоль, созданный с AllocConsole() на Windows 10 в WinMain , Примечание: я фактически не создал никакого реального окна. Что-то изменилось в Window 10, что предотвращает работу вышеупомянутых решений или есть что-то, чего я могу не хватать (флагов компилятора или что-то еще)?

Как вы думаете?

+1

Пожалуйста, не задавайте свой вопрос в ссылках на сайт. Пожалуйста, покажите код, который вы пробовали. Что вы ожидали, и что произошло. Поскольку это стоит, этот вопрос не в тему. –

+0

А когда я это сделаю, я получу 50 ответов, на которые уже был дан ответ [дубликат]. – Zingam

+0

Так что я добавил некоторые из кода, который я пробовал. – Zingam

ответ

4

На основании принятого ответа от ссылки ProXicT с несколькими изменениями. Следующий код работает для std :: cout. Другие методы не будут работать на 64-битных с Visual Studio 2015:

#include <iostream> 
#include <cstdio> 
#include <fstream> 

#include <Windows.h> 


// For debugging 
#include <io.h> 
#include <fcntl.h> 


#define UNUSED(x) (void)(x)  // Unused param (C compatible - not applicable to expressions) 

class outbuf : public std::streambuf { 
public: 
    outbuf() { 
     setp(0, 0); 
    } 

    virtual int_type overflow(int_type c = traits_type::eof()) { 
     return fputc(c, stdout) == EOF ? traits_type::eof() : c; 
    } 
}; 

int CALLBACK 
WinMain (HINSTANCE hInstance, 
     HINSTANCE /*hPrevInst*/, // Unused param (C++ only) 
     LPSTR lpCmdLine, 
     int (nShowCmd)) 
{ 
    UNUSED(hInstance); 
// UNUSED(hPrevInst); 
    UNUSED(lpCmdLine); 
    UNUSED(nShowCmd); // This param is used 


    // create the console 
    if (AllocConsole()) { 
     FILE* pCout; 
     freopen_s(&pCout, "CONOUT$", "w", stdout); 
     SetConsoleTitle(L"Debug Console"); 
     SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED); 
    } 

    // set std::cout to use my custom streambuf 
    outbuf ob; 
    std::streambuf *sb = std::cout.rdbuf(&ob); 

    // do some work here 
    printf("Hello!\n"); 

    std::cout << "nShowCmd = " << nShowCmd << std::endl; 
    std::cout << "Now making my first Windows window!" << std::endl; 


    // make sure to restore the original so we don't get a crash on close! 
    std::cout.rdbuf(sb); 

    MessageBoxW (NULL, 
       L"Hello World!", 
       L"hello", 
       MB_OK | MB_ICONINFORMATION); 

    return 0; 
} 

EDIT:

Тот же материал, как описано выше, но с цветами для полноты:

#include <iostream> 
#include <cstdio> 
#include <fstream> 

#include <Windows.h> 


// For debugging 
#include <io.h> 
#include <fcntl.h> 


#define UNUSED(x) (void)(x)  // Unused param (C compatible - not applicable to expressions) 

class outbuf : public std::streambuf { 
public: 
    outbuf() { 
     setp(0, 0); 
    } 

    virtual int_type overflow(int_type c = traits_type::eof()) { 
     return fputc(c, stdout) == EOF ? traits_type::eof() : c; 
    } 
}; 

int CALLBACK 
WinMain (HINSTANCE hInstance, 
     HINSTANCE /*hPrevInst*/, // Unused param (C++ only) 
     LPSTR lpCmdLine, 
     int (nShowCmd)) 
{ 
    UNUSED(hInstance); 
// UNUSED(hPrevInst); 
    UNUSED(lpCmdLine); 
    UNUSED(nShowCmd); // This param is used 


    // create the console 
    if (AllocConsole()) { 
     FILE* pCout; 
     freopen_s(&pCout, "CONOUT$", "w", stdout); 
     SetConsoleTitle(L"Debug Console"); 

    } 

    // set std::cout to use my custom streambuf 
    outbuf ob; 
    std::streambuf *sb = std::cout.rdbuf(&ob); 

    // do some work here 

    printf("Hello!\n"); 

    HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); 
    CONSOLE_SCREEN_BUFFER_INFO consoleInfo; 
    WORD defaultConsoleTextAttributes; 
    GetConsoleScreenBufferInfo(stdHandle, &consoleInfo); 
    defaultConsoleTextAttributes = consoleInfo.wAttributes; 
    WORD currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "nShowCmd = " << nShowCmd << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_BLUE; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_BLUE | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_RED; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_RED | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_BLUE; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_RED; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_BLUE | FOREGROUND_RED; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 
    currentConsoleTextAttributes = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY; 
    SetConsoleTextAttribute(stdHandle, currentConsoleTextAttributes); 
    std::cout << "Now making my first Windows window!" << std::endl; 



    // make sure to restore the original so we don't get a crash on close! 
    std::cout.rdbuf(sb); 

    Sleep(5000); 
    ShowWindow(GetConsoleWindow(), SW_HIDE); 
    FreeConsole(); 

    MessageBoxW (NULL, 
       L"Hello World!", 
       L"hello", 
       MB_OK | MB_ICONINFORMATION); 

    return 0; 
} 

Все, что остается в настоящее время является чтобы превратить его в полный класс ведения журнала.

5

Попробуйте этот код.

AllocConsole(); 
HANDLE stdHandle; 
int hConsole; 
FILE* fp; 
stdHandle = GetStdHandle(STD_OUTPUT_HANDLE); 
hConsole = _open_osfhandle((long)stdHandle, _O_TEXT); 
fp = _fdopen(hConsole, "w"); 

freopen_s(&fp, "CONOUT$", "w", stdout); 

printf("Hello console on\n"); 
std::cout << "Windows 10" << std::endl; 
+1

Примечание: '#include ' и ' #include 'требуется для вызова' _open_osfhandle' –

0

Если вы используете г ++, и вы хотите, чтобы ваше приложение всегда есть и консоль и графический интерфейс пользователя, то вы можете поставить компоновщик флаги как -mconsole и -mwindows для достижения этой цели.

See this answer для получения более подробной информации.

Смежные вопросы