gpt4 book ai didi

使用 Windows API 在控制台中居中文本?

转载 作者:可可西里 更新时间:2023-11-01 10:10:41 27 4
gpt4 key购买 nike

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

最佳答案

引用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

关于使用 Windows API 在控制台中居中文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57864423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com