delphidelphi-10.3-rio

Change text color in delphi (Console application)


I know the question I've asked seems similar to others however it doesn't seem to apply.

I am using delphi 10.3

I want to write two texts consecutively in the console application however I want them separate colors

writeln('yes just give me a minute, i need to talk to the manager'); {i want this in the default color}
writeln('Oi Dave we got another thick one shall i just pass him through as self employed'); {i want this to be in red}
writeln('Dont worry u dont have to complete this one') {and this one back to the default color}

Solution

  • You can use SetConsoleTextAttribute as already commented to the question. Example:

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils, winapi.windows;
    
    var
      ConOut: THandle;
      BufInfo: TConsoleScreenBufferInfo;
    begin
        writeln('yes just give me a minute, i need to talk to the manager');
    
        // get console screen buffer handle
        ConOut := TTextRec(Output).Handle;  // or GetStdHandle(STD_OUTPUT_HANDLE)
    
        // save current text attributes
        GetConsoleScreenBufferInfo(ConOut, BufInfo);
    
        // set foreground color to red
        SetConsoleTextAttribute(TTextRec(Output).Handle, FOREGROUND_INTENSITY or FOREGROUND_RED);
    
        writeln('Oi Dave we got another thick one shall i just pass him through as self employed');
    
        // reset to defaults
        SetConsoleTextAttribute(ConOut, BufInfo.wAttributes);
    
        writeln('Dont worry u dont have to complete this one');
        readln;
    end.
    


    Minimum required reading: SetConsoleTextAttribute and character attributes.

    Don't forget to add error handling.