首页 > 解决方案 > 使用Windows api在控制台中居中文本?

问题描述

有没有办法使用 windows API (windows.h) 在控制台窗口中将文本输出居中?

或者来自另一个库的函数,或者一般的可能性?

目前我插入了几个控制字符,但根据窗口的分辨率和大小,它不适合。

printf ("\n\t\t\t\t   --Men\x81--\n\n\t\t\t     1: Neue Spielrunde\n\t\t\t     2: Charaktere laden\n\t\t\t     3: Spielrunde speichern\n\t\t\t     4: Programm beenden\n\n");

标签: cwindows

解决方案


参考这个答案:

#include <windows.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void print_spaces(int n) {
    for (int i = 0; i < n; i++) printf(" ");
}

int main(void) {
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    int columns, rows, cols_by_2;

    // Get console window attributes - no. of columns in this case
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;

    cols_by_2 = columns / 2;

    // Put all options in an array
    char options[4][100] = {"1: Neue Spielrunde", "2: Charaktere laden", 
                            "3: Spielrunde speichern", "4: Programm beenden"};

    char menu_header[5] = "Men\x81";
    int len_header_by_2 = strlen(menu_header) / 2;

    print_spaces(cols_by_2 - len_header_by_2);
    printf("%s\n", menu_header);

    // Find max half-length of string
    int max_val = INT_MIN;
    for (int i = 0; i < 4; i++) {
        int len_str = strlen(options[i]) / 2;
        if (max_val < len_str)
            max_val = len_str;
    }

    // Compute spaces to add for max half-length string
    int no_of_spaces = cols_by_2 - max_val;

    // Print all options using computed spaces
    for (int i = 0; i < 4; i++) {
        print_spaces(no_of_spaces);
        printf("%s\n", options[i]);
    }
    return 0;
}

这是我测试底层逻辑的链接(不包括计算窗口属性):http: //ideone.com/KnPrct


推荐阅读