开发者

C# - Console Keystrokes

开发者 https://www.devze.com 2023-01-05 19:04 出处:网络
I want to compare the key pressed in a console to the left arrow key if they are equal meaning the key pressed was the left arrow key, key change the background color of the console to cyan...

I want to compare the key pressed in a console to the left arrow key if they are equal meaning the key pressed was the left arrow key, key change the background color of the console to cyan...

I'm not sure how to set up the If statement though, because I dont know how to compare 开发者_如何学运维keys in a console.

using System;

namespace ConsolePaint
{
class MainClass
{


    public static void Main (string[] args)
    {
        ConsoleKeyInfo keypress;
        keypress = Console.ReadKey(); // read keystrokes 

        if ( keypress.KeyChar == ConsoleKey.LeftArrow )
        {
            Console.BackgroundColor = "Cyan";
        }
    }
}

}


try this:

ConsoleKeyInfo keypress;
keypress = Console.ReadKey(); // read keystrokes 

if (keypress.Key == ConsoleKey.LeftArrow)
{
    Console.BackgroundColor = ConsoleColor.Cyan;
}


You need to use keypress.Key (instead of .KeyChar) - also your "Cyan" should be ConsoleColors.Cyan too.


Try this:

    ConsoleKeyInfo keypress;
    keypress = Console.ReadKey(); // read keystrokes 
    if ( (int)keypress.Key == (char)ConsoleKey.LeftArrow )
    {
        Console.BackgroundColor = ConsoleColor.Cyan;
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消