Is there a way to wait for and get a key press fro

2019-04-15 12:32发布

I've been playing around with some ANSI stuff (like colors etc.) in java and php (from scratch) and I'm trying to find a way to basically wait for a key press. I'd like to have something like the following pseudo code at the end of my main event loop:

If (KeyPressed)
Begin
    var event = new KeyboardEvent();
        event.Key = ReadKey();
    this.BubbleEvent(event);
End

But everything I've been trying over the last couple days fails because the key presses only become available on STDIN after the user has pressed enter.

It doesn't matter much what language you answer in, but java, php, plain old c or c# would be nicest, and I cannot use any really spiffy library stuff because I need to port it to all four of those languages... I need this to work over a telnet or ssh connection, but my research so far suggests it is impossible unless you're working on the local machine.

Please prove me wrong.

2条回答
时光不老,我们不散
2楼-- · 2019-04-15 12:46

The curses function cbreak(3) will disable line-buffering and erase/kill handling. You can do this yourself with stty(1) if you really want.

When your program dies and leaves the terminal in cbreak mode, you can usually use either stty sane or reset to bring the terminal back to a reasonable state.

From within Perl, you can use either the Term::ReadKey or the Curses module to manipulate the terminal. See the Term::ReadKey(3pm) or Curses(3pm) manpage for details.

From within C, you can use either ioctl(2) calls on the terminal device to turn on cbreak mode, or you can use curses. See the ncurses(3) manpage for details.

查看更多
▲ chillily
3楼-- · 2019-04-15 12:54

I know, this is an old thread, but I could not find a suitable answer anywhere else. So with some help from the senior programmers of my company I came up with this:

private void waitKeypress() throws IOException
{
    System.in.read();
    while ( System.in.available() > 0 ) 
    {
        System.in.read();
    }
}

The part reading as much input as is available solved my problem that when used multiple times, "System.in.read()" alone does not always wait.

For me this does the trick, I use it like this:

doSomething();
waitKeypress();
doNextThing();

Hope it helps.

Kind regards, Ralph

查看更多
登录 后发表回答