Keyboard input/Keypress check: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|ZX Spectrum BASIC}}: corrected language name)
(→‎Tcl: Added implementation)
Line 18: Line 18:
If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey().
If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey().
<lang PureBasic>k$ = Inkey()</lang>
<lang PureBasic>k$ = Inkey()</lang>

=={{header|Tcl}}==
There are two ways to handle listening for a key from the terminal. The first is to put the channel connected to the terminal into non-blocking mode and do a <code>read</code> on it:
<lang tcl>fconfigure stdin -blocking 0

set ch [read stdin 1]
if {$ch eq ""} {
# Nothing was read
} else {
# Got the character $ch
}</lang>
The second method is to set up an event listener to perform callbacks when there is at least one character available:
<lang tcl>fileevent stdin readable GetChar
proc GetChar {} {
set ch [read stdin 1]
if {[eof stdin]} {
exit
}
# Do something with $ch here
}

vwait forever; # run the event loop if necessary</lang>
Note that in both cases, if you want to get characters as users actually type them then you have to [http://wiki.tcl.tk/14693 put the terminal in raw mode]. That's formally independent of the actual reading of a character.

Revision as of 08:45, 11 October 2010

Keyboard input/Keypress check is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.

BASIC

ZX Spectrum Basic

<lang basic>10 REM k$ will be empty, if no key has been pressed 20 LET k$ = INKEY$</lang>

PureBasic

Returns a character string if a key is pressed during the call of Inkey(). It doesn't interrupt (halt) the program flow.

If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey(). <lang PureBasic>k$ = Inkey()</lang>

Tcl

There are two ways to handle listening for a key from the terminal. The first is to put the channel connected to the terminal into non-blocking mode and do a read on it: <lang tcl>fconfigure stdin -blocking 0

set ch [read stdin 1] if {$ch eq ""} {

   # Nothing was read

} else {

   # Got the character $ch

}</lang> The second method is to set up an event listener to perform callbacks when there is at least one character available: <lang tcl>fileevent stdin readable GetChar proc GetChar {} {

   set ch [read stdin 1]
   if {[eof stdin]} {
       exit
   }
   # Do something with $ch here

}

vwait forever; # run the event loop if necessary</lang> Note that in both cases, if you want to get characters as users actually type them then you have to put the terminal in raw mode. That's formally independent of the actual reading of a character.