C# - Console Keystrokes

佐手、 提交于 2019-12-08 00:57:14

问题


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";
        }
    }
}

}

回答1:


try this:

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

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



回答2:


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




回答3:


Try this:

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


来源:https://stackoverflow.com/questions/3169072/c-sharp-console-keystrokes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!