如何输出一个字符到控制台,而不是在C#后移动光标? [英] How to output a char to the console without moving the cursor afterwards in C#?

查看:343
本文介绍了如何输出一个字符到控制台,而不是在C#后移动光标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用C#(.NET 4.5)来制作控制台应用程序。我的问题是,游标总是移动到下一个单元格后使用Console.Write(char c),所以当它到达一行的最后一个单元格,它去到下一行,搞乱了所有的布局。

I am currently using C# (.NET 4.5) to craft a console application. The problem I have is that the cursor always moves to the next cell after using Console.Write(char c), so when it reaches the last cell of a line, it goes to the next line, messing up all the layout. Is it possible to output a char to the console (with background and foreground color) without moving the cursor afterwards?

我使用的代码如下:

Console.BackgroundColor = bgColor;
Console.ForegroundColor = fgColor;
Console.SetCursorPosition(currX, currY);
Console.Write(c);

假设currX和currY为整数,bgColor和fgColor为ConsoleColor,c为char。

Assume currX and currY as integers, bgColor and fgColor as ConsoleColor and c as a char.

谢谢。

推荐答案

根据 控制台类的文档,它提供只访问标准输出流,而不是屏幕缓冲区(虽然你可以改变缓冲区的一些属性,如它的大小)。 MoveBufferArea 是另一个明显的例外,但在这里 1 不适用。

According to the documentation of the Console class, it provides access only to the standard output stream, not to the screen buffer (although you can change some properties of the buffer, such as its size). And MoveBufferArea is another obvious exception, but doesn't really apply here1.

Win32 API提供对控制台缓冲区的访问。您可能希望p /调用 WriteConsoleOutput WriteConsoleOutputCharacter 。 (p /调用声明此处

The Win32 API does provide access to the console buffer. You would probably want to p/invoke WriteConsoleOutput or WriteConsoleOutputCharacter. (p/invoke declarations here)

值得注意的是:


WriteConsoleOutput

哦,你可能需要Unicode版本(以 W ),因为.NET字符串都是UTF-16。

Oh, you'll probably want the Unicode versions (ending in W) because .NET strings are all UTF-16.

1 它允许您以两种方式提供内容:内容已经在缓冲区 - 但首先是存在的问题,或者从提供的字符和属性 - 但是这只是用于填充源区域,而目标不是可选的。

1 It lets you provide content two ways: content already in the buffer -- but getting it there in the first place is the problem, or from a character and attribute provided -- but this is only used to fill the "source" area, and the destination is not optional.

这篇关于如何输出一个字符到控制台,而不是在C#后移动光标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆