[英]Is there a way to display text without setting cursor position
所以基本上,我想知道是否有一種無需設置光標位置即可顯示文本的方法
就像,如果我想在第5、7點顯示“ 0”
我知道我能做
Console.SetCursorPosition(5,7);
Console.Write("0");
但是我需要在程序中使用光標進行其他操作。 有沒有一種方法可以在我不顯示位置的情況下顯示0?
萬分感謝!
嘗試捕獲上一個位置,然后重新設置:
Console.WriteLine("abc");
var prevX = Console.CursorLeft;
var prevY = Console.CursorTop;
Console.SetCursorPosition(15, 17);
Console.Write("0");
Console.SetCursorPosition(prevX, prevY);
Console.ReadKey();
您必須為Console.Write
設置光標位置,才能知道實際寫入的位置。 因此,您無法避免使用SetCursorPosition
。 但是,您可以使用CursorLeft
和CursorTop
獲取當前位置,然后再恢復它們(如Giorgi的回答)。
您可以將所有內容包裝在一個方便的方法中,如下所示:
public static void WriteAt(string s, int x, int y)
{
// save the current position
var origCol = Console.CursorLeft;
var origRow = Console.CursorTop;
// move to where you want to write
Console.SetCursorPosition(x, y);
Console.Write(s);
// restore the previous position
Console.SetCursorPosition(origCol, origRow);
}
您將這樣使用:
WriteAt("foo",5,15);
您甚至可以使用這樣的擴展方法(不幸的是,您無法將擴展添加到Console
因為它是靜態類,但是您可以將其添加到String
!):
public static class StringConsoleHelper
{
public static void WriteAt(this string s, int x, int y)
{
// save the current position
var origCol = Console.CursorLeft;
var origRow = Console.CursorTop;
// move to where you want to write
Console.SetCursorPosition(x, y);
Console.Write(s);
// restore the previous position
Console.SetCursorPosition(origCol, origRow);
}
}
因此,現在您可以執行以下操作:
"foo".WriteAt(5,15);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.