How to interrupt Console.ReadLine

后端 未结 10 811
情歌与酒
情歌与酒 2020-11-28 11:34

Is it possible to stop the Console.ReadLine() programmatically?

I have a console application: the much of the logic runs on a different thread and in th

10条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 11:57

    I needed a solution that would work with Mono, so no API calls. I'm posting this just encase anyone else is in the same situation, or wants a pure C# way of doing this. The CreateKeyInfoFromInt() function is the tricky part (some keys are more than one byte in length). In the code below, ReadKey() throws an exception if ReadKeyReset() is called from another thread. The code below is not entirely complete, but it does demonstrate the concept of using existing Console C# functions to create an interuptable GetKey() function.

    static ManualResetEvent resetEvent = new ManualResetEvent(true);
    
    /// 
    /// Resets the ReadKey function from another thread.
    /// 
    public static void ReadKeyReset()
    {
        resetEvent.Set();
    }
    
    /// 
    /// Reads a key from stdin
    /// 
    /// The ConsoleKeyInfo for the pressed key.
    /// Intercept the key
    public static ConsoleKeyInfo ReadKey(bool intercept = false)
    {
        resetEvent.Reset();
        while (!Console.KeyAvailable)
        {
            if (resetEvent.WaitOne(50))
                throw new GetKeyInteruptedException();
        }
        int x = CursorX, y = CursorY;
        ConsoleKeyInfo result = CreateKeyInfoFromInt(Console.In.Read(), false);
        if (intercept)
        {
            // Not really an intercept, but it works with mono at least
            if (result.Key != ConsoleKey.Backspace)
            {
                Write(x, y, " ");
                SetCursorPosition(x, y);
            }
            else
            {
                if ((x == 0) && (y > 0))
                {
                    y--;
                    x = WindowWidth - 1;
                }
                SetCursorPosition(x, y);
            }
        }
        return result;
    }
    

提交回复
热议问题