Új hozzászólás Aktív témák

  • joysefke

    veterán

    LOGOUT blog

    válasz Pörp #8012 üzenetére

    Az egyetlen nehézséget az okozza ebben, hogy a Console.ReadKey() blokkol ha éppen nem volt megnyomva billentyű, ekkor addig vár amíg le nem nyomsz egy billenytűt, azt kiolvassa és csak azután megy tovább a végrehajtás. A Console.KeyAvailable segítségével ezt ki lehet küszöbölni, ennek akkor ha true az értéke, akkor volt lenyomva billentyű, amelynek az értéke bufferbe került, ezt ki lehet olvasni a Console.ReadKey()-jel, anélkül, hogy az blokkolna.

    using System;
    using System.Threading;

    // NonblockingReadKey
    class Program
    {
    // N > 1
    static void Count(int N)
    {
    //this will store the pressed key
    ConsoleKeyInfo consoleKey;

    // counter will be the running variable
    // starting to count down from N
    int counter = N;

    // when true: counting down
    // when false counting up
    bool countingDown = true;

    // ends one below zero when counting down and one above N when counting up
    while (!(counter==-1 && countingDown) && !(counter == N+1 && !countingDown) )
    {
    Console.Clear();
    Console.Write(counter);
    Thread.Sleep(250);

    // Console.KeyAvailable == true only if there was a keypress
    //in the console
    if (Console.KeyAvailable)
    {
    // reads the keypress
    consoleKey= Console.ReadKey();
    // reads any remaining keypresses from the buffer
    // if you have pressed more then one keys during sleep-time
    while (Console.KeyAvailable) consoleKey = Console.ReadKey();

    // Immediatelly breaks at reading ESC key
    if (consoleKey.Key == ConsoleKey.Escape)
    { Console.Clear(); break; }

    //switches the counting direction
    // true -> false
    // false -> true
    // countingDown ^= true; ;)
    countingDown = !countingDown;

    }

    //increments or decrements the counter according to
    // the value of countingDown
    if (countingDown == true) { --counter; }
    else { ++counter; }
    }
    Console.Clear();
    Console.WriteLine("Finished!!!");

    }
    static void Main(string[] args)
    {
    Count(100);
    }
    }

    [ Szerkesztve ]

Új hozzászólás Aktív témák