我的C#控制台项目有问题.我想使用整个控制台屏幕在其中写入文本.例如,意味着沿着控制台的边界"绘制"边框.问题是最后一行中不必要的最后一个字符.我该怎样预防呢?
为了更好地理解,我添加了一个不需要的角色的图片.
我通过填充二维chars数组并使用以下方法转储它来绘制它.yMax是控制台窗口的高度和xMax的宽度.
private void DumpCharacters() { for (int y = 0; y < yMax - 1; y++) { string line = string.Empty; for (int x = 0; x < xMax; x++) { line += characters[x, y]; } Console.SetCursorPosition(0, y); Console.Write(line); } }
我已经尝试增加边框的高度,但随后,提到的字符会覆盖该位置的边框.
编辑: 对不起我的解释不清楚.当然,就像AttilaBujáki所说,我的意思是跳到最后一行.有可能阻止这种情况吗?
使用CursorVisible属性Console
Console.CursorVisible = false;
如果要用字符填充整个控制台窗口,一种可行的方法是将光标移回0,0位置。
例:
Console.CursorVisible = false; for(int i = 0; i < Console.WindowHeight * Console.WindowWidth; i ++) { Console.Write((i / Console.WindowWidth) % 10); // print your stuff } Console.SetCursorPosition(0, 0); Console.ReadKey();
因此,您可以在您的方法中这样做:
private void DumpCharacters() { for (int y = 0; y < yMax; y++) { string line = string.Empty; for (int x = 0; x < xMax; x++) { line += characters[x, y]; } Console.SetCursorPosition(0, y); Console.Write(line); } Console.SetCursorPosition(0, 0); }
注意,您不必从yMax中减去一个。这是因为现在您也可以使用“控制台”屏幕的最后一行。
这是生成所需结果的完整代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleChar { class Program { static void Main(string[] args) { Console.Title = "Stackoverflow - Super example"; Console.CursorVisible = false; int yMax = Console.WindowHeight; int xMax = Console.WindowWidth; char[,] characters= new char[Console.WindowWidth, Console.WindowHeight]; for (int i = 0; i < Console.WindowWidth; i++ ) { for (int j = 0; j < Console.WindowHeight; j++) { char currentChar = ' '; if((i == 0) || (i == Console.WindowWidth - 1)) { currentChar = '?'; } else { if((j == 0) || (j == Console.WindowHeight - 1)) { currentChar = '?'; } } characters[i, j] = currentChar; } } characters[0, 0] = '?'; characters[Console.WindowWidth-1, 0] = '?'; characters[0, Console.WindowHeight - 1] = '?'; characters[Console.WindowWidth - 1, Console.WindowHeight - 1] = '?'; for (int y = 0; y < yMax ; y++) { string line = string.Empty; for (int x = 0; x < xMax; x++) { line += characters[x, y]; } Console.SetCursorPosition(0, y); Console.Write(line); } Console.SetCursorPosition(0, 0); } } }