【问题标题】:Center text in console with windows api?使用Windows api在控制台中居中文本?
【发布时间】:2020-01-11 20:02:45
【问题描述】:

有没有办法使用 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");

【问题讨论】:

  • 你需要找到终端窗口的宽度(cmd)。见this

标签: c windows


【解决方案1】:

参考this答案:

#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

【讨论】:

    【解决方案2】:

    如果您愿意,您实际上可以完全控制 win32 控制台上的图形。实际上,您最终会调用 AllocConsole,然后调用 FillConsoleOutputAttribute 来设置文本的颜色属性,并使用 FillConsoleOutputCharacter 来指定要显示的字符。但是,这确实意味着您最终会完全避免使用 cout/cin/printf/scanf,这可能是也可能不是问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-21
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 2013-04-26
      • 1970-01-01
      • 2022-01-15
      相关资源
      最近更新 更多