C ++缓冲区备份失败

c++ buffer backup failure

我正在开发一个控制台 C++ 项目,我需要在其中备份控制台缓冲区的一个区域,以便我可以编辑它并在完成后还原更改。我想出了这两个函数,但都有问题,因为第一个输出错误代码 1 [ERROR_INVALID_FUNCTION 1 (0x1) Incorrect function] 而第二个输出 87 [ERROR_INVALID_PARAMETER 87 (0x57) The parameter is incorrect] 根据 MSDN error code list. I also checked the documentation for ReadConsoleOutput and WriteConsoleOutput API 但我找不到解决方案。

void backupBuffer(PCHAR_INFO buffer, COORD pos, COORD size) {
    SMALL_RECT rect = { pos.X,  pos.Y, pos.X + size.X - 1, pos.Y + size.Y - 1 };
    COORD buffer_index = { 0, 0 };
    BOOL success = 
    ReadConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
                      buffer,
                      buffer_index,
                      pos,
                      &rect);
    if (!success) {
        int error = GetLastError();
                    cout << error << endl;
    }
}

void setBuffer(PCHAR_INFO buffer, COORD pos, COORD size) {
    SMALL_RECT rect = { pos.X,  pos.Y, pos.X + size.X - 1, pos.Y + size.Y - 1 };
    COORD buffer_index = { 0, 0 };
    BOOL success =
    WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),
                       buffer,
                       buffer_index,
                       pos,
                       &rect);
    if (!success) {
        int error = GetLastError();
        cout << error << endl;
    }
}

调用如下:

// width = 10, height = 10 and the console
// window dimensions are 30 x 120 but the buffer
// height should be bigger since I'm able to scroll
// down for a while before reaching the end. 
PCHAR_INFO buffer = new CHAR_INFO[width * height];
COORD pos, size;
pos.X = 20; pos.Y = 2;
size.X = width; size.Y = height;
backupBuffer(buffer, pos, size);

// Visual Stuff (cout in that area...)

setBuffer(buffer, pos, size);

我应该怎么做才能解决这个问题?

在你的两个函数中你有:

COORD buffer_index = { 0, 0 };

该参数需要指定字符信息块的大小(在CHAR_INFOs中)。现在你告诉它没有 space 副本。