在 delphi 中更改文本颜色(控制台应用程序)

Ben*_*ley 6 delphi delphi-10.3-rio

我知道我问的问题似乎与其他问题相似,但似乎并不适用。

我在用 delphi 10.3

我想在控制台应用程序中连续写两个文本但是我希望它们分开颜色

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}
Run Code Online (Sandbox Code Playgroud)

Ser*_*yuz 5

您可以使用SetConsoleTextAttribute已经评论过的问题。例子:

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.
Run Code Online (Sandbox Code Playgroud)


最低要求阅读:SetConsoleTextAttribute字符属性

不要忘记添加错误处理。