Search code examples
consoleconsole-applicationeiffel

Read key in Eiffel console application


Is there anything like Console.ReadKey from .NET in Eiffel on Windows?

I need a way to read input from the console without waiting for the user to press Enter.

The function io.read_character cannot be used because it blocks until the user presses Enter.


Solution

  • As explained in answers on SO (here or here) as well as elsewhere, there is no portable way to read a character from a console without waiting. However you can easily use any of the approaches listed in the links by interfacing to external code from Eiffel. The following example demonstrates how to do it on Windows:

    read_char: CHARACTER
            -- Read a character from a console without waiting for Enter.
        external "C inline use <conio.h>"
            alias "return getch ();"
        end
    

    Then the feature read_char can be called from your code as a regular one:

            from
                io.put_string ("Press q or Esc to exit.")
                io.put_new_line
            until
                c = 'q' or c = '%/27/'
            loop
                c := read_char
                io.put_string ("You pressed: ")
                if c = '%U' or c = '%/224/' then
                        -- Extended key is pressed, read next character.
                    c := read_char
                    io.put_string ("extended key ")
                    io.put_natural_32 (c.natural_32_code)
                else
                    io.put_character (c)
                end
                io.put_new_line
            end