Daniel
Daniel

Reputation: 197

Reading the keys form a keyboard C#

I have a console app in C# that does a animation with a word, in a loop. Its basically showing the word going from left to righ. My idea is that if the user press upArrow the animation would start to go up , if he press left the word would satrt to go left... and so on My question is, how can i have a loop running and also have the program listen for the keyboard key that will be pressed at any given moment?

Upvotes: 1

Views: 539

Answers (2)

Mahmood Shahrokni
Mahmood Shahrokni

Reputation: 236

I wrote a good and considerable code for you although you need to complete it yourself. It just follows the order of the Left Arrow key. You need to add some extra code for following the other orders. Also you have to care about indexoutofrangeexception. As you can see I have written some extra code to handle the left side of console. I hope you enjoy it.

static void Main(string[] args)
{
    const string txt = "STACKOVERFLOW";
    var x = 1;
    var startPos = 0;
    var col = 0;
    while (true)
    {
        do
        {
            while (!Console.KeyAvailable && (startPos <= 100 || startPos >= 0))
            {

                startPos = col + x;
                if (startPos < 0)
                {
                    startPos = 0;
                    x = 1;
                }
                Console.SetCursorPosition(startPos, 0);
                Console.WriteLine(txt);
                col = startPos;
                Thread.Sleep(500);
                Console.Clear();
            }
        } while (Console.ReadKey(true).Key != ConsoleKey.LeftArrow);
        x = -1;

    }
}

Upvotes: 1

jose h.
jose h.

Reputation: 1

I don't know if you have found a solution for your program yet, but here is a good tutorial you might find useful.

Basic C# Game Programming Moving Object on the form

Upvotes: 0

Related Questions