trapping a key before it gets to the Console

*爱你&永不变心* 提交于 2019-12-11 19:56:56

问题


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)


来源:https://stackoverflow.com/questions/21339822/trapping-a-key-before-it-gets-to-the-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!