Answer to Question #260242 in C# for Kiyemba Marvin

Question #260242

Write a C# program to detect key presses. If the user pressed number keys( from 0 to 9), the 

program will display the number that is pressed, otherwise the program will show "Not allowed". 


1
Expert's answer
2021-11-02T08:23:31-0400
using System;

namespace Test
{
    class KeyPress
    {
        static int Main()
        {
            Console.WriteLine("Press number key");

            while(true)
            {
                ConsoleKeyInfo info = Console.ReadKey(true);

                if(info.Key == ConsoleKey.Escape)
                {
                    break;
                }

                switch(info.Key)
                {
                    case ConsoleKey.D0: case ConsoleKey.D1: case ConsoleKey.D2: 
                    case ConsoleKey.D3: case ConsoleKey.D4: case ConsoleKey.D5: 
                    case ConsoleKey.D6: case ConsoleKey.D7: case ConsoleKey.D8: 
                    case ConsoleKey.D9: Console.WriteLine(info.KeyChar); break;
                    default: Console.WriteLine("Not allowed"); break;
                }
            }

            return 0;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS