Skip to main content
 首页 » 编程设计

c#之如何使我的所有输出以及我的光标都集中在 Visual Studios 中

2024年02月25日65zhenyulu

我正在尝试创建一种交互式菜单(我过去所有的代码)。 当用户输入信息时,如何使输出文本居中并确保光标居中?

为了使我的输出居中,我使用了很多空间。 至于将光标居中,我不知道从哪里开始。

目前只使用了大量空间

Console.WriteLine("\r\n\r\n                                  Welcome, Please Enter An Encrypted Message Using:"); 
Console.WriteLine("\r\n                                                     @ For A"); 
Console.WriteLine("\r\n                                                     # For E"); 
Console.WriteLine("\r\n                                                     ^ For I"); 
Console.WriteLine("\r\n                                                     * For O"); 
Console.WriteLine("\r\n                                                     + For U"); 

请您参考如下方法:

您可以尝试使用 Console.SetCursorPosition 方法进行一些计算,让单词居中。

static void SetTextCentre(string s) { 
    Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop); 
    Console.WriteLine(s); 
} 

然后在 Main 函数中使用。

static void Main(string[] args) 
{ 
 
    SetTextCenter("Welcome, Please Enter An Encrypted Message Using:"); 
    SetTextCenter("@ For A"); 
    SetTextCenter("# For E"); 
    SetTextCenter("^ For I"); 
    SetTextCenter("* For O"); 
    SetTextCenter("+ For U"); 
 
    Console.ReadKey(); 
} 

注意

Console.SetCursorPosition 方法中有两个参数。

public static void SetCursorPosition(int left, int top)

如果你想设置中心你需要关注第一个参数。

  • Console.WindowWidth 获取当前控制台窗口的宽度和长度。

  • (Console.WindowWidth - s.Length)/2 获取居中的字长。