Console output with WinAPI WriteConsole

11,359

This is a GUI application that you force to act like a console application. I'm guessing cmd.exe (or whatever the parent is) is getting confused as you both think you "own" stdout.

Link with /SUBSYSTEM:CONSOLE and the problems should go away (and then you don't need /ENTRY or the call to AttachConsole)

If you actually want a GUI/Console hybrid, you need to call AllocConsole when there is no console (Started from Explorer etc)

Share:
11,359
Pyjong
Author by

Pyjong

Updated on June 04, 2022

Comments

  • Pyjong
    Pyjong almost 2 years

    I'm trying to do hello world with winapi functions. It's kind of working but I would love to have it done the proper way.

    So i got code like this:

    int main(){
        HANDLE std_out;
        int i;
        char *error_msg;
    
        std_out = GetStdHandle(STD_OUTPUT_HANDLE);
    
        if(std_out == INVALID_HANDLE_VALUE){
            MessageBox(NULL,"stdout not available","Error",MB_OK);
            return 1;
        }
    
        AttachConsole(ATTACH_PARENT_PROCESS);
    
        if(!WriteConsoleA(std_out,"hhh\n",4,&i,NULL)){
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,NULL,GetLastError(),0,&error_msg,4,NULL);
            MessageBox(NULL,error_msg,"Error",MB_OK);
        }
    
        return 42;
    }
    

    Also I'm a little bit experimenting so I link with /entry:main /subsystem:windows

    the output is then like:

    %PATH_TO_WORKING_DIR%>hhh(CRLF)
    

    then it waits until I press RETURN and then the program terminates, which as you probably agree is very crapy "hello world". Any ideas how to get rid of that PWD and necessity to press return are very welcomed, thx for reading.