如何使用 WriteConsoleOutputCharacter() 从文本中清除区域

How to clear an area from text with WriteConsoleOutputCharacter()?

本文关键字:文本 清除 区域 何使用 WriteConsoleOutputCharacter      更新时间:2023-10-16

所以,我有一个表示矩形的C++类,我使用输出速度比coutprintf()更快的WriteConsoleOutputCharacter函数,我已经制作了一个打印矩形的程序,但我在清除矩形时遇到了问题。

根据我对 msdn 的理解,此函数可以从控制台的当前代码页打印 unicode 字符或 8 位字符。无论如何,当我想打印退格键以清除矩形时,它不起作用,它会打印其他内容(◘(。当我尝试通过它的十六进制代码 (0x008( 打印退格键时,它再次打印了该符号。

代码非常简单:

const char clr[] ="b";//Thar the array I'm printing 

void rect_m::clr_ar()
{
    Ex = Vx + Lx;//These variables are the rectangle's sizes
    Ey = Vy + Ly;
    HANDLE mout = GetStdHandle(STD_OUTPUT_HANDLE);
        //The loops cover the rectangle area
    for (SHORT i = Vy; i < Ey; i++)
    {
        for (SHORT j = Vx; j < Ex; j++)
        {
            WriteConsoleOutputCharacter(mout, clr, strlen(clr), { j,i }, &dwWritten);
        }
    }

}

好吧,我想要的只是一种使用 WriteConsoleOutputCharacter 函数打印退格键以清除文本的方法(而不是在其上打印空格(。我知道这是一个非常基本的错误,并且有更好的方法。那么,有人可以告诉我我的代码有什么问题吗?

对于清晰的矩形区域,我们可以使用 ScrollConsoleScreenBufferW 用空白字符填充选定的矩形。 请注意,空白字符等于空白空间,我们可以在测试中查看空白,如果在开始时调用ReadConsoleOutputCharacter 在空控制台上:

COORD xy{};
ULONG n;
WCHAR c;
ReadConsoleOutputCharacterW(hConsoleOutput, &c, 1, xy, &n);
//c == ' ';

所以完整的代码可以看起来像:

BOOL cls(const SMALL_RECT* lpScrollRectangle = 0)
{
    HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    if (GetConsoleScreenBufferInfo(hConsoleOutput, &csbi))
    {
        CHAR_INFO fi = { ' ', csbi.wAttributes };
        if (!lpScrollRectangle)
        {
            csbi.srWindow.Left = 0;
            csbi.srWindow.Top = 0;
            csbi.srWindow.Right = csbi.dwSize.X - 1;
            csbi.srWindow.Bottom = csbi.dwSize.Y - 1;
            lpScrollRectangle = &csbi.srWindow;
        }
        return ScrollConsoleScreenBufferW(hConsoleOutput, lpScrollRectangle, 0, csbi.dwSize, &fi);
    }
    return FALSE;
}