2

我想比较控制台中按下的键与左箭头键是否相等,这意味着按下的键是左箭头键,键将控制台的背景颜色更改为青色...

我不确定如何设置 If 语句,因为我不知道如何在控制台中比较键。

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

}
4

3 回答 3

4

尝试这个:

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

if (keypress.Key == ConsoleKey.LeftArrow)
{
    Console.BackgroundColor = ConsoleColor.Cyan;
}
于 2010-07-02T21:06:10.313 回答
1

您需要使用keypress.Key(而不是.KeyChar)-您也"Cyan"应该使用ConsoleColors.Cyan

于 2010-07-02T21:07:35.210 回答
0

尝试这个:

    ConsoleKeyInfo keypress;
    keypress = Console.ReadKey(); // read keystrokes 
    if ( (int)keypress.Key == (char)ConsoleKey.LeftArrow )
    {
        Console.BackgroundColor = ConsoleColor.Cyan;
    }
于 2010-07-02T21:10:34.950 回答