user2979104
user2979104

Reputation: 13

Creating a rectangle that is a certain amount of pixels in width and height in Console Application using C#

how do i create a red rectangle in console application that is a certain amount of pixels in width and height.

I have found ways to do it but not in a way that i can decide how many pixels it is in widht and height. If you can please help me with my problem.

I have tried almost anything that comes up on google and somw things that i tried myslef.

I thought of this but that doesnt specify the amount of pixels and i cant change the amount either:

Console.OutpuEncoding = Encoding.GetEncoding(866);
Console.Writeline("┌─┐");
Console.WriteLine("│1│");
Console.WriteLine("└─┘");

Upvotes: 1

Views: 421

Answers (1)

Maciej Stachowski
Maciej Stachowski

Reputation: 1728

Okay. I don't know if the following code will always work, crash, or eat your firstborn, but here it is - drawing a rectangle in a console window, the C# way. Hacked in a few minutes and not optimal by any means, but you can adapt it to your needs.

namespace ConsoleApplication12
{
class Program
{

    [DllImport("gdi32.dll")]
    private extern static int SetPixel(int hdc, int x, int y, int color);

    [DllImport("kernel32.dll")]
    private extern static int GetConsoleWindow();

    [DllImport("user32.dll")]
    private extern static int GetDC(int i);

    static void Main(string[] args)
    {
        int myCon = GetConsoleWindow();
        int myDC = GetDC(myCon);
        for (int i = 50; i < 150; i++)
        {
            for (int j = 50; j < 150; j++)
            {
                if (i == 50 || i == 149 || j == 50 || j == 149)
                    SetPixel(myDC, i, j, 255*256*256 + 255*256 + 255);
            }
        }
        Console.ReadLine();
    }
}
}

Upvotes: 2

Related Questions