C# Working with the Console

C# Code Snippets Working with the console
Share:

About

In this code snippet, we will learn the basics of how to work with the console in C#.

We will see how to write text to the console, read text from the console, change the text and background color and change the cursor position.

Let’s have a look at the code below to see work with the console.

Code:

using System;


namespace WorkingWithTheConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            //Sets the background color.
            Console.BackgroundColor = ConsoleColor.Gray;
            //Sets the text color.
            Console.ForegroundColor = ConsoleColor.Red;

            //Writes text to the conssole.
            Console.Write("Hi.");

            //Writes text to a new line in the conssole.
            Console.WriteLine();
            Console.WriteLine("Hi.");

            //Set the cursor postion.
            Console.SetCursorPosition(10,10);
            
            Console.WriteLine("Enter something.");
            //Waits for user to input a string and press enter.
            string inputStr = Console.ReadLine();
            Console.WriteLine(inputStr);

            Console.WriteLine("Press a key.");
            //Gets the key pressed by the user.
            char key = Console.ReadKey().KeyChar;
            Console.WriteLine("The " + key +" key was pressed");

            //Makes a beep.
            Console.Beep(2000, 500); //(frequency, time of beep)

            //At the end of your program if you want for the console window to stay open add:
            Console.ReadLine(); //Or ReadKey()
            //The console will now wait for your input before closing.
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger