Getting terminal size in c for windows?

后端 未结 3 1087
野趣味
野趣味 2020-11-28 08:45

How to check ymax and xmax in a console window, under Windows, using plain c?

There is this piece of code for linux:

         


        
3条回答
  •  野性不改
    2020-11-28 09:15

    This prints the size of the console, not the buffer:

    #include 
    
    int main(int argc, char *argv[]) {
        CONSOLE_SCREEN_BUFFER_INFO csbi;
        int columns, rows;
    
        GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
        columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
        rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
    
        printf("columns: %d\n", columns);
        printf("rows: %d\n", rows);
        return 0;
    }
    

    This code works because srWindow "contains the console screen buffer coordinates of the upper-left and lower-right corners of the display window", and the SMALL_RECT structure "specify the rows and columns of screen-buffer character cells" according to MSDN. I subtracted the parallel sides to get the size of the console window. Since I got 1 less than the actual value, I added one.

提交回复
热议问题