Home > Net >  How to run code when the user presses a specific key c#
How to run code when the user presses a specific key c#

Time:06-06

how do I make this work properly? What do i need to include in my using at the top? And is this even possible?

internal class Program
{
    int money = 10;
    public void Water()
    {
        Console.WriteLine("You spent $5 on water");
        money -= 5;
    }
    static void Main(string[] args)
    {
        Console.WriteLine("To buy water press the w key");
        if(// w key is pressed)
        {
            Water();
        }

        //wait before closing
        Console.ReadKey();
    }
}

CodePudding user response:

Maybe you meant something like this:

internal class Program
{
    static int money = 20;
    
    static void Main(string[] args)
    {
        Console.WriteLine(BuyWater());
    }

    public static string BuyWater()
    {

        while (money > 0)
        {
            Console.WriteLine("To buy water press the w key");
//this is where your pressed key comes in:
            if (Console.ReadKey(true).Key == ConsoleKey.W)      // (true) is for not showing the pressed key in the console
            {
                Console.WriteLine("You spent $5 on water");
                money -= 5;
            }

            Console.WriteLine("You have $"   money);

        }
        return "You have no money left";
    }
}

CodePudding user response:

Console.ReadKey do exactly what you need.

Console.WriteLine("Press w to buy water");

if (Console.ReadKey().Key == ConsoleKey.W)
    Water();
  •  Tags:  
  • c#
  • Related