2015-05-27 152 views
1

所以基本上显示文本的方式,我想知道是否有不设置光标位置有没有设置光标位置

像显示文本的方式,如果我想显示“0”点5,7

我知道我可以做

Console.SetCursorPosition(5,7); 
Console.Write("0"); 

但我需要我的光标别人在我的计划什么。有没有一种方法可以在不设置位置的情况下显示0?

谢谢!

+0

有你阅读下面的C#MSDN方法的文档'Console.SetCursorPostions' https://msdn.microsoft.com/en-我们/库/ system.console.setcursorposition%28V = vs.110%29.aspx – MethodMan

回答

4

尝试捕捉上一个位置,然后重新设定:

Console.WriteLine("abc"); 

var prevX = Console.CursorLeft; 
var prevY = Console.CursorTop; 

Console.SetCursorPosition(15, 17); 
Console.Write("0"); 

Console.SetCursorPosition(prevX, prevY); 

Console.ReadKey(); 
3

必须设置光标位置Console.Write知道在哪里实际编写。所以你不能避免使用SetCursorPosition。但是,您可以使用CursorLeftCursorTop获得当前位置,然后恢复它们(如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);