This program is given in following website.
http://www.dotnetperls.com/console-readkey
This new code (info.KeyChar == 'X') instead of (info.Key == ConsoleKey.X) is giving different last line output. Please explain the reason. Code is highlighted.
using System;
class Program
{
static void Main()
{
Console.WriteLine("... Press escape, a, then control X");
// Call ReadKey method and store result in local variable.
// ... Then test the result for escape.
ConsoleKeyInfo info = Console.ReadKey();
if (info.Key == ConsoleKey.Escape)
{
Console.WriteLine("You pressed escape!");
}
// Call ReadKey again and test for the letter a.
info = Console.ReadKey();
if (info.KeyChar == 'a')
{
Console.WriteLine("You pressed a");
}
// Call ReadKey again and test for control-X.
// ... This implements a shortcut sequence.
info = Console.ReadKey();
if (info.Key == ConsoleKey.X && info.Modifiers == ConsoleModifiers.Control)
{
Console.WriteLine("You pressed control X");
}
Console.Read();
}
}
/*
... Press escape, a, then control X
?You pressed escape!
aYou pressed a
?You pressed control X
*/
Loading
VulpesPosted Jul 5, 2013, 5:08 PM
Now Control-X does in fact represent the unicode character 24 so, if you press this key combination, then the KeyChar property returns (char)24 and not 'X' which is (char)88.
So, if you replace this line:
if (info.Key == ConsoleKey.X && info.Modifiers == ConsoleModifiers.Control)
with this:
if (info.KeyChar == (char)24 && info.Modifiers == ConsoleModifiers.Control)
or even just this:
if (info.KeyChar == (char)24)
then the output will be just the same.
However, if you replace it with:
if (info.KeyChar == 'X' && info.Modifiers == ConsoleModifiers.Control)
then the output will be different (it won't say 'You pressed control X') because the KeyChar property doesn't return 'X'.
Posted Jul 5, 2013, 5:32 PM