Create window console inside main win32 window

后端 未结 4 1960
有刺的猬
有刺的猬 2021-02-20 02:20

I have a win32 application that need to open a console like the games when tilde is pressed. I tought that the best solution is to use the CreateWindow function. Is this right?

4条回答
  •  滥情空心
    2021-02-20 02:30

    The solutions here won't work because newer versions of the Windows SDK define the FILE structure by:

    #ifndef _FILE_DEFINED
        #define _FILE_DEFINED
        typedef struct _iobuf
        {
            void* _Placeholder;
        } FILE;
    #endif
    

    When trying to overwrite the stdin/out FILE structures with the = operator, only one pointer will be copied. To copy the whole FILE struct, you have to define the FILE structure before your windows.h include:

    #ifndef _FILE_DEFINED
    struct _iobuf {
            char *_ptr;
            int   _cnt;
            char *_base;
            int   _flag;
            int   _file;
            int   _charbuf;
            int   _bufsiz;
            char *_tmpfname;
            };
    typedef struct _iobuf FILE;
    #define _FILE_DEFINED
    #endif
    
    #include 
    

    If this is somehow not possible for you, you can still define your own FILE structure as FILE_COMPLETE and use this codesnippet:

    #include 
    #include 
    #include 
    
    AllocConsole();
    SetConsoleTitleA("ConsoleTitle");
    typedef struct { char* _ptr; int _cnt; char* _base; int _flag; int _file; int _charbuf; int _bufsiz; char* _tmpfname; } FILE_COMPLETE;
    *(FILE_COMPLETE*)stdout = *(FILE_COMPLETE*)_fdopen(_open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT), "w");
    *(FILE_COMPLETE*)stderr = *(FILE_COMPLETE*)_fdopen(_open_osfhandle((long)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w");
    *(FILE_COMPLETE*)stdin = *(FILE_COMPLETE*)_fdopen(_open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r");
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);
    setvbuf(stdin, NULL, _IONBF, 0);
    

提交回复
热议问题