Search code examples
c#consolepositiontext-cursor

Cursor position in c#


I'm just a beginner so sorry if my question is stupid. I'm making program that will ask about rectangle's size (AxB) and will draw it. But I need it to also ask about rectangle's position (X,Y). Is there any way to set a cursor position in c# console app that will work longer than only for an upper part of a rectangle? Or something simple that will make it happen? Here's part of a code:

int a;
int b;
int x;
int y;
Console.WriteLine("A");
a = int.Parse(Console.ReadLine());
Console.WriteLine("B");
b = int.Parse(Console.ReadLine());
Console.WriteLine("X");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Y");
y = int.Parse(Console.ReadLine());
Console.Clear();
Console.SetCursorPosition(x, y);
for (int i = 0; i < a; i++)
    Console.Write("*");
Console.Write("\n");
for (int i = 0; i < b - 2; i++)
{
    Console.Write("*");
    for (int k = 0; k < a - 2; k++)
        Console.Write(" ");
    Console.Write("*");
    Console.Write("\n");
}
for (int i = 0; i < a; i++)
    Console.Write("*");
Console.Write("\n");   

Solution

  • This is by far not the most efficient or elegant solution, but it will work for what you are looking to do:

            int a;
            int b;
            int x;
            int y;
            Console.WriteLine("A");
            a = int.Parse(Console.ReadLine());
            Console.WriteLine("B");
            b = int.Parse(Console.ReadLine());
            Console.WriteLine("X");
            x = int.Parse(Console.ReadLine());
            Console.WriteLine("Y");
            y = int.Parse(Console.ReadLine());
            Console.Clear();
            Console.SetCursorPosition(x, y);
    
            for (int i = 0; i < y; i++) //this for will print all the "y" line breaks before your picture prints
            {
                Console.Write("\n");
            }
    
            for (int j = 0; j < x; j++)
            {
                Console.Write(" ");
            }
    
            for (int i = 0; i < a; i++)
                Console.Write("*");
            Console.Write("\n");
    
            for (int i = 0; i < b - 2; i++)
            {
                for (int j = 0; j < x; j++) //This for will print x spaces before each line
                {
                    Console.Write(" ");
                }
                Console.Write("*");
                for (int k = 0; k < a - 2; k++)
                    Console.Write(" ");
                Console.Write("*");
                Console.Write("\n");
            }
            for (int j = 0; j < x; j++)
            {
                Console.Write(" ");
            }
            for (int i = 0; i < a; i++)
                Console.Write("*");
            Console.Write("\n");
    
            Console.ReadLine();
    

    Just needed to print some extra line breaks and spaces in the right places