3

我想获取控制台窗口的内容。我得到了以下代码,但它不起作用,,.. 谁能告诉我如何获取控制台内容(字符)??????

    DWORD nLength=2;
    HWND hWnd = FindWindow("ConsoleWindowClass",NULL);
    LPTSTR lpCharacter=" ";
    COORD dwReadCoord;
    dwReadCoord.X=11;
    dwReadCoord.Y=11;
    LPDWORD lpNumberOfCharsRead=0;
    bool a= ReadConsoleOutputCharacter(hWnd,lpCharacter,nLength,dwReadCoord,lpNumberOfCharsRead);
4

1 回答 1

0

这是一种方法。GetNumCharsInConsoleBuffer是获取控制台缓冲区中的字符数。使用该值创建一个动态分配的数组。最后ReadConsoleBuffer将用控制台缓冲区的内容填充您的缓冲区。

#include <cstdio>
#include <cstdlib>
#include <Windows.h>

DWORD GetNumCharsInConsoleBuffer()
{
    CONSOLE_SCREEN_BUFFER_INFO buffer_info;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &buffer_info);
    return (DWORD)((buffer_info.dwSize.X * ( buffer_info.dwCursorPosition.Y + 1)) - (buffer_info.dwSize.X - (buffer_info.dwCursorPosition.X  + 1)));
}

DWORD ReadConsoleBuffer(char* buffer, DWORD bufsize)
{
    DWORD num_character_read = 0;
    COORD first_char_to_read = {0};  
    ReadConsoleOutputCharacterA(GetStdHandle(STD_OUTPUT_HANDLE), buffer, bufsize, first_char_to_read, &num_character_read);
    buffer[bufsize-1] = '\0';

    return num_character_read;
}

int main(int argc, char** argv)
{
    fprintf(stdout, "Writting\nin\nthe\nbuffer\n");

    DWORD bufsize = GetNumCharsInConsoleBuffer();   
    char* buffer = new char[bufsize];
    memset(buffer, 0, bufsize);

    ReadConsoleBuffer(buffer, bufsize);    
    puts("\nBuffer contents:");
    puts(buffer);

    delete[] buffer;
    system("pause"); 
    return 0;

}

输出:

Writting
in
the
buffer
Buffer contents:
Writting
in
the
buffer

Appuyez sur une touche pour continuer...
于 2016-11-05T00:00:12.167 回答