Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active March 20, 2023 06:50
Show Gist options
  • Save sunmeat/5ffdcc6c001bfb59e943ad16cfc6d0f8 to your computer and use it in GitHub Desktop.
Save sunmeat/5ffdcc6c001bfb59e943ad16cfc6d0f8 to your computer and use it in GitHub Desktop.
character background and foreground color in particular coordinates C# console application example
using System.Runtime.InteropServices;
class Tester
{
public static void GetColor(short y, short x, uint length = 1)
{
var colors = new ushort[1];
uint numberOfCharactersRead;
if (ReadConsoleOutputAttribute(GetStdHandle(-11), colors, length, new Coord(x, y), out numberOfCharactersRead))
{
Console.Title = "Colors in coordinates [" + x + "," + y +
"] - Background: " + (ConsoleColor)(colors[0] / 16) +
" Foreground: " + (ConsoleColor)(colors[0] % 16);
Console.ReadKey();
}
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadConsoleOutputAttribute(IntPtr hConsoleOutput, [Out] ushort[] lpAttribute, uint length, Coord bufferCoord, out uint lpNumberOfCharactersRead);
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X;
public short Y;
public Coord(short x, short y)
{
X = x;
Y = y;
}
}
public static void Filler()
{
var r = new Random();
for (int i = 0; i < 1000; i++)
{
Console.SetCursorPosition(r.Next(20), r.Next(10));
Console.BackgroundColor = (ConsoleColor)r.Next(16);
Console.ForegroundColor = (ConsoleColor)r.Next(16);
Console.Write("@");
}
}
public static void Main()
{
Filler();
GetColor(0, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment