我想将控制台中光标的位置设置为最后一条可见线。我怎么能这样做?
干杯,
皮特
答案 0 :(得分:18)
如果您指的是窗口的最后一行,则可以混合使用Console.CursorTop
,Console.WindowHeight
和Console.WindowTop
。示例代码:
using System;
class Test
{
static void Main()
{
Console.Write("Hello");
WriteOnBottomLine("Bottom!");
Console.WriteLine(" there");
}
static void WriteOnBottomLine(string text)
{
int x = Console.CursorLeft;
int y = Console.CursorTop;
Console.CursorTop = Console.WindowTop + Console.WindowHeight - 1;
Console.Write(text);
// Restore previous position
Console.SetCursorPosition(x, y);
}
}
请注意,这必须考虑Console.WindowTop
以找出您在缓冲区中的位置......
答案 1 :(得分:1)
我还必须解决这个问题并提出来:
public class Program
{
static int id = 0 , idOld = 0, idSelected = -1;
static string[] samples;
public static void Main()
{
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WindowWidth = 90;
Console.WindowHeight = 36;
Console.WindowTop = 5;
Console.Title = "My Samples Application";
Console.InputEncoding = Encoding.GetEncoding("windows-1251");
samples = new string[50];
for (int i = 0; i < samples.Length; i++)
samples[i] = "Sample" + i;
LoopSamples();
}
static void SelectRow(int y, bool select)
{
Console.CursorTop = y + 1;
Console.ForegroundColor = select ? ConsoleColor.Red : ConsoleColor.Yellow;
Console.WriteLine("\t{0}", samples[y]);
Console.CursorTop = y;
}
static void LoopSamples()
{
int last = samples.Length - 1;
ShowSamples();
SelectRow(0, true);
while (true)
{
while (idSelected == -1)
{
idOld = id;
ConsoleKey key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.UpArrow:
case ConsoleKey.LeftArrow: if (--id < 0) id = last; break;
case ConsoleKey.DownArrow:
case ConsoleKey.RightArrow: if (++id > last) id = 0; break;
case ConsoleKey.Enter: idSelected = id; return;
case ConsoleKey.Escape: return;
}
SelectRow(idOld, false);
SelectRow(id, true);
}
}
}
static void ShowSamples()
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Use arrow keys to select a sample. Then press 'Enter'. Esc - to Quit");
for (int i = 0; i < samples.Length; i++)
Console.WriteLine("\t{0}", samples[i]);
}
}