[Haskell-cafe] Re: Trapping getChar before echo

Judah Jacobson judah.jacobson at gmail.com
Fri Feb 5 18:38:52 EST 2010


On Fri, Feb 5, 2010 at 10:41 AM, Andrew Coppin
<andrewcoppin at btinternet.com> wrote:
> Tim Attwood wrote:
>>>
>>> Last time I tried something like this [on Windows], it didn't seem to
>>> work. I wanted to trap arrow keys and so forth, but they seem to be being
>>> used for input history. (I.e., pressing the up-arrow produces
>>> previously-entered lines of text, and none of this appears to be reaching
>>> the Haskell program itself.) Has this changed since I tried it last year?
>>
>> Doesn't work in windows, at least up till 6.10.1. There's a work-around
>> though.
>>
>> {-# LANGUAGE ForeignFunctionInterface #-}
>>
>> import Data.Char
>> import Control.Monad (liftM, forever)
>> import Foreign.C.Types
>>
>> getHiddenChar = liftM (chr.fromEnum) c_getch
>> foreign import ccall unsafe "conio.h getch"
>>  c_getch :: IO CInt
>>
>> main = do
>>  forever $ do
>>     c <- getHiddenChar
>>     putStrLn $ show (fromEnum c)
>
> Thanks for the info.
>
> Does anyone know how this is related to the "haskeline" package on Hackage?

The haskeline package provides a readline-like library for reading in
a line of input with arrow keys, tab completion, etc.  It works on
both Windows and unix platforms.  Documentation and a full list of
features can be found at http://trac.haskell.org/haskeline/ .

On Windows, haskeline gets all user input by calling Win32 API
functions such as ReadConsoleInputW:

http://msdn.microsoft.com/en-us/library/ms684961%28VS.85%29.aspx

That function returns an INPUT_RECORD struct with information about
key press events (among others); those includes simple characters,
arrow keys, page up/down, etc.  AFAIK that's the only way to get at
such events in the Windows console; there's no effective analogue to
the unix setting, where e.g. pressing the up key causes stdin to
receive the ANSI key sequence "\ESC[A".

The source code of haskeline has examples of how to import and use
those API functions:
http://code.haskell.org/haskeline/System/Console/Haskeline/Backend/Win32.hsc

Best,
-Judah


More information about the Haskell-Cafe mailing list