簡體   English   中英

C#移動Console.ReadLine()的位置

[英]C# Move the positon of Console.ReadLine()

我正在嘗試在控制台應用程序中創建輸入和輸出部分。 我需要完成的結果看起來像這樣: http : //i.imgur.com/H2lpRor.jpg

我將如何創建它,甚至有可能? 這是控制台應用程序所必需的。 另外,我將如何清除Console.ReadLine()所在的區域?

是的,有可能,您可以將CursorPosition設置為屏幕上的任意位置,然后將其設置回底部以進行輸入

Console.SetCursorPosition(Console.WindowLeft, Console.WindowBottom);

底部可能為-1

您可能還想看看https://github.com/AnthonyMastrean/ConsoleEx

您的方法有些不正確。 您缺乏使用舊DOS控制台的經驗,並且無法使用內置功能,而忘記了該控制台基於流並且可以手動操作。

當您需要實現自己的文本輸入布局時,就需要放棄內置的行讀取方法並切換到手動流操作。 幸運的是,.NET使事情比以前的老式COM更加容易。

例如,您可以從以下代碼開始,該代碼將文本輸入移動並將輸出管理為五行。 當然,它遠非完美(無限循環……靜態變量……讓我感到羞恥),但我將其保留為原始形式以使其更簡單。

為了將其轉換為多線程應用程序,您將需要使“輸出”線程安全(有很多方法可以做到)並更改Foo()的內容(當前僅是echo)。

class Program
{
    static List<string> output = new List<string>();
    static int maxlines = 5;
    static void Foo(string s)
    {
        // echo
        output.Add(s);
        while (output.Count>maxlines)
        {
            output.RemoveAt(0);
        }
    }
    static void Main(string[] args)
    {
        string s = "";
        while (true)
        {
            if (Console.KeyAvailable)
            {
                char c = Console.ReadKey(true).KeyChar;
                switch (c)
                {
                    case '\r': Foo(s); s = ""; break;
                    case '\b': if (s.Length > 0) { s = s.Remove(s.Length - 1); } break;
                    default: s += c; break;
                }
                // some clearing
                Console.SetCursorPosition(Console.WindowLeft, 6);
                Console.Write("                                                                 ");
                // and write current "buffer"
                Console.SetCursorPosition(Console.WindowLeft, 6);
                Console.Write(s);
            }
            // now lets handle our "output stream"
            for (int i = 0; i < Math.Min(maxlines, output.Count); i++)
            {
                Console.SetCursorPosition(Console.WindowLeft, i);
                Console.Write(output[i].PadRight(32));
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM