Preventing characters displayed in the terminal

I'm making a dumb terminal game that uses keyboard input to control a character moving around the board. When a user presses a key, my code responds correctly using getChar , but the character that users press also appears in the terminal. Is there a way to get keyboard input in a terminal application without displaying what the user has typed?

Edit: I am on a Mac, but it would be useful to know on all platforms.

+4
source share
1 answer

Basically you have to do two things to achieve your goal:

  • You need to disable any buffering in the terminal so that your program immediately presses the keys (and you do not need to confirm with ENTER).

     hSetBuffering stdin NoBuffering 
  • Then you must make sure that the character is not recalled back to the terminal.

     hSetEcho stdin False 

Please note that before exiting your program, it must restore the previous settings in order to allow further use of the terminal.

The code combination will look like this:

 import System.IO import Control.Exception (bracket) withHiddenTerminalInput :: IO a -> IO a withHiddenTerminalInput io = bracket (do prevBuff <- hGetBuffering stdin prevEcho <- hGetEcho stdin hSetBuffering stdin NoBuffering hSetEcho stdin False return (prevBuff, prevEcho) ) (\(prevBuff, prevEcho) -> do hSetBuffering stdin prevBuff hSetEcho stdin prevEcho ) (const io) 
+9
source

All Articles