1

Is there in Java the possibility to get what a user press "when it presses" and not when he hits return?

So, for example, if a user hit ABC and then hit Ctrl+Z I want that the program ends there (end of stream reached) and not, after, when he presses return.

Baz
  • 36,440
  • 11
  • 68
  • 94
xdevel2000
  • 20,780
  • 41
  • 129
  • 196
  • Possible duplicate: http://stackoverflow.com/questions/811851/how-do-i-read-input-character-by-character-in-java ? – david a. Sep 13 '12 at 10:37
  • You can create a gui application in which there is only lines, as so you can listen to the user interactions. – bouhmid_tun Sep 13 '12 at 12:03
  • 1
    possible duplicate of [How to read a single char from the console in Java (as the user types it)?](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – Neil Sep 13 '12 at 23:42

1 Answers1

4

Windows doesn't actually end the stream when you press Ctrl+Z; you can continue to edit the line and the application will only see the end of the stream when you press Return.

This is slightly different to Unix where Ctrl+D will send the current buffered line to the application (without a newline) and the application will only perceive the end of the stream when you send an empty buffer by pressing Ctrl+D either after a Return or after another Ctrl+D.

Edit: On Windows, you might be able to use the SetConsoleMode function to allow you to read single characters. I'm not sure how you would call it though; there appear to be three choices:

  1. Via JNI to a DLL that calls SetConsoleMode
  2. Invoke a program that calls SetConsoleMode
  3. Wrap your program in a launcher that calls SetConsoleMode
  4. Edit: Use JNA to call SetConsoleMode.
Neil
  • 54,642
  • 8
  • 60
  • 72
  • Yes. Thanks but you answer only a part of my question. So is not possible with Java to detect a key when it's pressed? – xdevel2000 Sep 13 '12 at 14:00