You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台程序切换全屏后如何自动居中文本?

C#控制台全屏模式下文本自动居中实现方案

一、先实现全屏切换

要将控制台切换为全屏模式,直接利用Console类的属性设置即可,无需复杂API调用:

// 设置缓冲区大小匹配最大窗口尺寸,消除滚动条
Console.SetBufferSize(Console.LargestWindowWidth, Console.LargestWindowHeight);
// 将窗口设置为系统支持的最大尺寸(全屏)
Console.WindowWidth = Console.LargestWindowWidth;
Console.WindowHeight = Console.LargestWindowHeight;

二、文本居中核心逻辑

文本居中的关键是动态计算光标起始位置:

  • 水平居中:用控制台窗口宽度减去文本长度,取一半作为水平偏移量
  • 垂直居中:取控制台窗口高度的一半作为垂直偏移量

封装成复用方法更方便:

static void WriteCentered(string text)
{
    if (string.IsNullOrWhiteSpace(text)) return;

    // 计算水平起始位置,确保不会出现负数偏移
    int horizontalStart = Math.Max(0, (Console.WindowWidth - text.Length) / 2);
    // 计算垂直起始位置
    int verticalStart = Console.WindowHeight / 2;

    // 定位光标并输出文本
    Console.SetCursorPosition(horizontalStart, verticalStart);
    Console.WriteLine(text);
}

三、完整示例代码

using System;

class FullScreenCenteredText
{
    static void Main()
    {
        // 切换全屏
        Console.SetBufferSize(Console.LargestWindowWidth, Console.LargestWindowHeight);
        Console.WindowWidth = Console.LargestWindowWidth;
        Console.WindowHeight = Console.LargestWindowHeight;
        Console.CursorVisible = false; // 可选:隐藏光标提升视觉效果

        // 输出居中内容
        string displayText = "控制台全屏居中文本示例";
        WriteCentered(displayText);

        Console.ReadKey();
    }

    static void WriteCentered(string text)
    {
        if (string.IsNullOrWhiteSpace(text)) return;

        int horizontalStart = Math.Max(0, (Console.WindowWidth - text.Length) / 2);
        int verticalStart = Console.WindowHeight / 2;

        Console.SetCursorPosition(horizontalStart, verticalStart);
        Console.WriteLine(text);
    }
}

四、多行文本居中扩展

如果需要多行文本垂直居中,可以先计算总行数,再调整垂直起始位置:

static void WriteMultiLineCentered(string[] lines)
{
    if (lines == null || lines.Length == 0) return;

    int verticalStart = Console.WindowHeight / 2 - lines.Length / 2;

    foreach (string line in lines)
    {
        int horizontalStart = Math.Max(0, (Console.WindowWidth - line.Length) / 2);
        Console.SetCursorPosition(horizontalStart, verticalStart++);
        Console.WriteLine(line);
    }
}

内容的提问来源于stack exchange,提问作者skrafi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:50:31