Keyboard input/Keypress check: Difference between revisions

From Rosetta Code
Content added Content deleted
(added PowerShell)
(Added PicoLisp)
Line 17: Line 17:
=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>if key? [make "keyhit readchar]</lang>
<lang logo>if key? [make "keyhit readchar]</lang>

=={{header|PicoLisp}}==
<lang PicoLisp>(setq *LastKey (key))</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==

Revision as of 16:23, 19 October 2010

Task
Keyboard input/Keypress check
You are encouraged to solve this task according to the task description, using any language you may know.

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>

Forth

<lang forth>variable last-key

check key? if key last-key ! then ;</lang>

<lang logo>if key? [make "keyhit readchar]</lang>

PicoLisp

<lang PicoLisp>(setq *LastKey (key))</lang>

PowerShell

The following uses the special $Host variable which points to an instance of the PowerShell host application. Since the host's capabilities may vary this may not wok in all PowerShell hosts. In particular, this works in the console host, but not in the PowerShell ISE. <lang powershell>if ($Host.UI.RawUI.KeyAvailable) {

   $key = $Host.UI.RawUI.ReadKey()

}</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] fconfigure stdin -blocking 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.