trapping a key before it gets to the Console

2019-09-02 03:09发布

问题:

THE SETTING:

A Console program, in .net

I am using readkey in a loop, which rewrites to the same line on the screen (Console.setCursorPosition)

however, if I type Enter, the Console pushes the text upwards, which is the usual command line behaviour.

THE QUESTION:

Is it possible to trap a key press (that Enter), so that my program will get the key, but the Console does not?

The environment is Linux, with Mono (and the program is supposed to be cross platform). so low level windows driver intercepting is not an option.

PS: I know the method of clearing and redrawing everything. I would like to know if my question is possible.

Thank you for any information

回答1:

Console.ReadKey(true) should read the key but not show it.



回答2:

after modifying code found here https://stackoverflow.com/a/8898251/1951298 I came to something that may help you, you see that when user pushes Enter the cursor doesn't increment, and nothing is written into console

ConsoleKeyInfo keyinfo;
    int left, top=0;
    do
    {
        left =  Console.CursorLeft;
        top =  Console.CursorTop;
        keyinfo = Console.ReadKey(true);


        if(keyinfo.Key.ToString().Equals("Enter"))
             Console.SetCursorPosition(left,top-1);
        else
             Console.WriteLine(keyinfo.Key + " was pressed");

    }
    while (keyinfo.Key != ConsoleKey.X);


回答3:

You should intercept the key press. MSDN Documentation

var PressedKey = Console.ReadKey(true)