trapping a key before it gets to the Console

2019-09-02 03:43发布

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

3条回答
Animai°情兽
2楼-- · 2019-09-02 03:48

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);
查看更多
Luminary・发光体
3楼-- · 2019-09-02 04:03

You should intercept the key press. MSDN Documentation

var PressedKey = Console.ReadKey(true)
查看更多
祖国的老花朵
4楼-- · 2019-09-02 04:09

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

查看更多
登录 后发表回答