Question

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?

The code I am using is the following:

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

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

Thankyou.

Was it helpful?

Solution

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.

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

Notably:

WriteConsoleOutput has no effect on the cursor position.

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


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.

OTHER TIPS

Try something like...

Console.Write("b");
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Console.Write("c");

For me, this just prints prints b, then replaces it with c. Effectively, the first two lines together write to the console without moving the cursor. You can conclude this because when you write c, it overwrites the b rather than placing it at the next position.

You could even write a helper method:

static void WriteWithoutMove(string s) 
{
    Console.Write(s);
    Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}

Is this what you're looking for?

I remember the old DOS, with the OLD command (for example) BASIC:

locate(21,50)
print "Qty[26]";

Note: The (;) use for stick the cursor for the text and add 1 char, if you use the (,) is TAB (CHR$(8))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top