1

In Output screen, When I press 2, then it prints D2.

Why It prints D before output? I am using Visual studio 2019.

using System;
using System.Collections.Generic;
using System.Text;

namespace CSharp5
{
    class Class3
    {
        static void Main()
        {
            ConsoleKeyInfo m = Console.ReadKey();
            Console.WriteLine("\n" + m.Key);
        }
    }
}
  • 2
    That is the value of the Enum: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?view=netframework-4.8 – Jacob Lambert Jun 15 '19 at 06:40

2 Answers2

3

Because Key is used to determine which key has pressed.

If you press for example the A key you will get 'A' in output but there are two 2 keys on a standard keyboard. One is on top of keyboard and other one is on number pad.

Key represents Key Enum, by this you are able to determine which 2 key has pressed.

If you press 2 on top of keyboard you will get D2 in output.

If you press 2 on number pad you will get NumPad2 in output.

If you need exact '2' on output use KeyChar instead of key.

static void Main(string[] args)
{

    ConsoleKeyInfo m = Console.ReadKey();
    Console.WriteLine("\r\n Console key is:" + m.Key);
    Console.WriteLine("\r\n Unicode character is:" + m.KeyChar);
    Console.ReadKey();
}
Progman
  • 16,827
  • 6
  • 33
  • 48
Masoud Keshavarz
  • 2,166
  • 9
  • 36
  • 48
1

You want the KeyChar property rather than Key. Key is the enum representing the character and enum names (like other names in C#) can't start with a number. KeyChar is the unicode character representing the key pressed.

Andy Lamb
  • 2,151
  • 20
  • 22