Keyboard input/Keypress check: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 9: Line 9:
{{works with|https://skilldrick.github.io/easy6502/ Easy6502}}
{{works with|https://skilldrick.github.io/easy6502/ Easy6502}}
Easy6502 uses zero page address FF as a memory-mapped port for keyboard input. The ASCII value of the last key you pressed is stored in this address, independent of the program's current execution state.
Easy6502 uses zero page address FF as a memory-mapped port for keyboard input. The ASCII value of the last key you pressed is stored in this address, independent of the program's current execution state.
<lang 6502asm>define sysLastKey $ff
<syntaxhighlight lang="6502asm">define sysLastKey $ff


main:
main:
Line 28: Line 28:
dex
dex
bne delay
bne delay
rts</lang>
rts</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 39: Line 39:
=={{header|Action!}}==
=={{header|Action!}}==
The KEY variable returns the key code, or 255 if no key was pressed.
The KEY variable returns the key code, or 255 if no key was pressed.
<lang Action>Proc Main()
<syntaxhighlight lang="action">Proc Main()
Byte KEY,k=764
Byte KEY,k=764
KEY=K
KEY=K
Return</lang>
Return</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>Ch : Character;
<syntaxhighlight lang="ada">Ch : Character;
Available : Boolean;
Available : Boolean;


Ada.Text_IO.Get_Immediate (Ch, Available);</lang>
Ada.Text_IO.Get_Immediate (Ch, Available);</syntaxhighlight>


If key was pressed, Available is set to True and Ch contains the value.
If key was pressed, Available is set to True and Ch contains the value.
Line 56: Line 56:
=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!
Version: hopper-FLOW!
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <flow.h>
#include <flow.h>


Line 71: Line 71:
PRNL( "Last key pressed: ", c )
PRNL( "Last key pressed: ", c )
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 84: Line 84:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* Programme assembleur ARM Raspberry */
/* Programme assembleur ARM Raspberry */
Line 481: Line 481:
bx lr @return
bx lr @return


</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
Waits for the user to type a string (not supported on Windows 9x: it does nothing).
Waits for the user to type a string (not supported on Windows 9x: it does nothing).
<lang AutoHotkey>; Input [, OutputVar, Options, EndKeys, MatchList]
<syntaxhighlight lang="autohotkey">; Input [, OutputVar, Options, EndKeys, MatchList]
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds</lang>
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds</syntaxhighlight>




Checks if a keyboard key or mouse/joystick button is down or up. Also retrieves joystick status.
Checks if a keyboard key or mouse/joystick button is down or up. Also retrieves joystick status.
<lang AutoHotkey>; GetKeyState, OutputVar, KeyName [, Mode]
<syntaxhighlight lang="autohotkey">; GetKeyState, OutputVar, KeyName [, Mode]
GetKeyState, State, RButton ; Right mouse button.</lang>
GetKeyState, State, RButton ; Right mouse button.</syntaxhighlight>




Function version of GetKeyState.
Function version of GetKeyState.
<lang AutoHotkey>; KeyIsDown := GetKeyState("KeyName" [, "Mode"])
<syntaxhighlight lang="autohotkey">; KeyIsDown := GetKeyState("KeyName" [, "Mode"])
State := GetKeyState("RButton", "P") ; Right mouse button. P = Physical state.</lang>
State := GetKeyState("RButton", "P") ; Right mouse button. P = Physical state.</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: TAWK -f KEYBOARD_INPUT_KEYPRESS_CHECK.AWK
# syntax: TAWK -f KEYBOARD_INPUT_KEYPRESS_CHECK.AWK
BEGIN {
BEGIN {
Line 519: Line 519:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 529: Line 529:
=={{header|Axe}}==
=={{header|Axe}}==
Note that while the syntax for getting the most recent keypress is identical to [[#TI-83_BASIC|TI-83 BASIC]], the keycodes themselves are different.
Note that while the syntax for getting the most recent keypress is identical to [[#TI-83_BASIC|TI-83 BASIC]], the keycodes themselves are different.
<lang axe>getKey→K</lang>
<syntaxhighlight lang="axe">getKey→K</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K)</lang>
<syntaxhighlight lang="applesoftbasic">K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K)</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===
<lang freebasic>
<syntaxhighlight lang="freebasic">
PRINT "Press <escape> to exit now..."
PRINT "Press <escape> to exit now..."
key = GETKEY
key = GETKEY
IF key = 27 THEN
IF key = 27 THEN
END
END
END IF</lang>
END IF</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>do
<syntaxhighlight lang="freebasic">do
k$ = key
k$ = key
until k$ <> ""
until k$ <> ""
Line 553: Line 553:
else
else
print "An extended key was pressed"
print "An extended key was pressed"
end if</lang>
end if</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> key$ = INKEY$(0)</lang>
<syntaxhighlight lang="bbcbasic"> key$ = INKEY$(0)</syntaxhighlight>
If there was no keypress an empty string is returned. Alternatively a numeric key-code may be obtained; if there was no keypress -1 is returned:
If there was no keypress an empty string is returned. Alternatively a numeric key-code may be obtained; if there was no keypress -1 is returned:
<lang bbcbasic> key% = INKEY(0)</lang>
<syntaxhighlight lang="bbcbasic"> key% = INKEY(0)</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 LET K$=INKEY$</lang>
<syntaxhighlight lang="is-basic">100 LET K$=INKEY$</syntaxhighlight>


or
or


<lang IS-BASIC>100 GET K$</lang>
<syntaxhighlight lang="is-basic">100 GET K$</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>DO: k$ = INKEY$: LOOP UNTIL k$ <> ""
<syntaxhighlight lang="qbasic">DO: k$ = INKEY$: LOOP UNTIL k$ <> ""
PRINT k$</lang>
PRINT k$</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
Line 575: Line 575:


<code>inkey$</code> may only be used, if <code>clear screen</code> has been called at least once.
<code>inkey$</code> may only be used, if <code>clear screen</code> has been called at least once.
<lang yabasic>clear screen
<syntaxhighlight lang="yabasic">clear screen
k$ = inkey$</lang>
k$ = inkey$</syntaxhighlight>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
{{works with|Locomotive Basic}}
{{works with|Locomotive Basic}}


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




=={{header|C}}==
=={{header|C}}==
For POSIX systems. Ctrl-C to stop:<lang C>#include <stdio.h>
For POSIX systems. Ctrl-C to stop:<syntaxhighlight lang="c">#include <stdio.h>
#include <termios.h> /* general terminal interface: tcgetattr, tcsetattr, tcflush */
#include <termios.h> /* general terminal interface: tcgetattr, tcsetattr, tcflush */
#include <unistd.h> /* synchronous I/O multiplexing: select, FD_CLR, FD_ISSET, FD_SET, FD_ZERO */
#include <unistd.h> /* synchronous I/O multiplexing: select, FD_CLR, FD_ISSET, FD_SET, FD_ZERO */
Line 634: Line 634:
printf("key %d\n", c);
printf("key %d\n", c);
}
}
}</lang>
}</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
==={{header|ncurses}}===
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<lang lisp>(defun keypress-check ()
<syntaxhighlight lang="lisp">(defun keypress-check ()
(with-screen (scr :input-echoing nil :input-blocking nil :input-buffering nil :enable-function-keys t)
(with-screen (scr :input-echoing nil :input-blocking nil :input-buffering nil :enable-function-keys t)
(loop
(loop
Line 655: Line 655:
(refresh scr)
(refresh scr)
;; we wait anyway to spare the CPU.
;; we wait anyway to spare the CPU.
(sleep 0.15))))))</lang>
(sleep 0.15))))))</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>string chr = string.Empty;
<syntaxhighlight lang="csharp">string chr = string.Empty;
if(Console.KeyAvailable)
if(Console.KeyAvailable)
chr = Console.ReadKey().Key.ToString();</lang>
chr = Console.ReadKey().Key.ToString();</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 669: Line 669:
<pre>$ lein trampoline run</pre>
<pre>$ lein trampoline run</pre>


<lang clojure>
<syntaxhighlight lang="clojure">
(ns keypress.core
(ns keypress.core
(:import jline.Terminal)
(:import jline.Terminal)
Line 686: Line 686:
(prompt)
(prompt)
(shutdown-agents))
(shutdown-agents))
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
<lang d>extern (C) {
<syntaxhighlight lang="d">extern (C) {
void _STI_conio();
void _STI_conio();
void _STD_conio();
void _STD_conio();
Line 704: Line 704:


_STD_conio();
_STD_conio();
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
This is valid for a GUI application!
This is valid for a GUI application!
<lang Delphi>unit Unit1;
<syntaxhighlight lang="delphi">unit Unit1;


interface
interface
Line 735: Line 735:
end;
end;


end.</lang>
end.</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
{{trans|C#}}
{{trans|C#}}
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;


public program()
public program()
Line 749: Line 749:
chr := console.readChar()
chr := console.readChar()
}
}
}</lang>
}</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
!$KEY
!$KEY
.........
.........
GET(K$)
GET(K$)
.........
.........
</syntaxhighlight>
</lang>
Note: If no key was pressed K$ is empty string "".
Note: If no key was pressed K$ is empty string "".


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>integer key
<syntaxhighlight lang="euphoria">integer key
key = get_key() -- if key was not pressed get_key() returns -1</lang>
key = get_key() -- if key was not pressed get_key() returns -1</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<lang fsharp>open System;
<syntaxhighlight lang="fsharp">open System;


let chr = if Console.KeyAvailable then Console.ReadKey().Key.ToString() else String.Empty</lang>
let chr = if Console.KeyAvailable then Console.ReadKey().Key.ToString() else String.Empty</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>variable last-key
<syntaxhighlight lang="forth">variable last-key
: check key? if key last-key ! then ;</lang>
: check key? if key last-key ! then ;</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim k As String
Dim k As String
Line 788: Line 788:
End If
End If


Sleep</lang>
Sleep</syntaxhighlight>


Sample input/output
Sample input/output
Line 798: Line 798:


=={{header|Gambas}}==
=={{header|Gambas}}==
<lang gambas>Public Sub Form_KeyPress()
<syntaxhighlight lang="gambas">Public Sub Form_KeyPress()


'Requires a TextBox or similar on the Form to work
'Requires a TextBox or similar on the Form to work
Print Key.Text;
Print Key.Text;


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 811: Line 811:
=={{header|Go}}==
=={{header|Go}}==
{{libheader|Curses}}
{{libheader|Curses}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 833: Line 833:
s.Refresh()
s.Refresh()
time.Sleep(500 * time.Millisecond)
time.Sleep(500 * time.Millisecond)
}</lang>
}</syntaxhighlight>


s.Println()
s.Println()
Line 853: Line 853:
s.GetChar()
s.GetChar()
You don't need external dependencies to achieve this. You can use a channel and set a timeout on it.
You don't need external dependencies to achieve this. You can use a channel and set a timeout on it.
::<lang go>package main
::<syntaxhighlight lang="go">package main
// stackoverflow.com/questions/43965556/how-to-read-a-key-in-go-but-continue-application-if-no-key-pressed-within-x-seco
// stackoverflow.com/questions/43965556/how-to-read-a-key-in-go-but-continue-application-if-no-key-pressed-within-x-seco
import (
import (
Line 883: Line 883:
fmt.Println("Time out!")
fmt.Println("Time out!")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Concurrent
<syntaxhighlight lang="haskell">import Control.Concurrent
import Control.Monad
import Control.Monad
import Data.Maybe
import Data.Maybe
Line 905: Line 905:
else putStrLn "Awaiting char.." >>
else putStrLn "Awaiting char.." >>
threadDelay 500000 >> wait c
threadDelay 500000 >> wait c
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 916: Line 916:


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
delay(1000) # give user a chance to input
delay(1000) # give user a chance to input
if kbhit() then # test for input
if kbhit() then # test for input
Line 922: Line 922:
else # use getche for echo
else # use getche for echo
write("No input waiting")
write("No input waiting")
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==


(Note that keypress handling depends on the host. Here, we illustrate jqt.)<lang J>wd'pc p closeok;cc c isidraw;pshow;'
(Note that keypress handling depends on the host. Here, we illustrate jqt.)<syntaxhighlight lang="j">wd'pc p closeok;cc c isidraw;pshow;'
p_c_char=: {{variable=: sysdata}}</lang>
p_c_char=: {{variable=: sysdata}}</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|java|8}}
{{works with|java|8}}
<lang java>import java.awt.event.*;
<syntaxhighlight lang="java">import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;


Line 953: Line 953:
});
});
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
<lang javaScript>
let thePressedKey;
let thePressedKey;


Line 965: Line 965:


document.addEventListener('keydown', handleKey);
document.addEventListener('keydown', handleKey);
</syntaxhighlight>
</lang>


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>using Gtk
<syntaxhighlight lang="julia">using Gtk


function keypresswindow()
function keypresswindow()
Line 989: Line 989:


keypresswindow()
keypresswindow()
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
Translated from the Java entry but then modified so as to quit the program when the Enter key is pressed:
Translated from the Java entry but then modified so as to quit the program when the Enter key is pressed:
<lang scala>// version 1.1
<syntaxhighlight lang="scala">// version 1.1


import java.awt.event.KeyAdapter
import java.awt.event.KeyAdapter
Line 1,023: Line 1,023:
f.isVisible = true
f.isVisible = true
}
}
}</lang>
}</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>-- in some movie script
<syntaxhighlight lang="lingo">-- in some movie script


-- event handler
-- event handler
Line 1,032: Line 1,032:
pressedKey = _key.key
pressedKey = _key.key
put "A key was pressed:" && pressedKey
put "A key was pressed:" && pressedKey
end</lang>
end</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
Line 1,038: Line 1,038:


Example
Example
<lang LiveCode>repeat 100 times
<syntaxhighlight lang="livecode">repeat 100 times
-- exit loop if "." or the escapeKey is pressed
-- exit loop if "." or the escapeKey is pressed
if 46 is in the keysDown or 65307 is in the keysdown then
if 46 is in the keysDown or 65307 is in the keysdown then
Line 1,047: Line 1,047:
wait 200 millisec
wait 200 millisec
end if
end if
end repeat</lang>
end repeat</syntaxhighlight>
Example of event message handling (at stack, card or control level)
Example of event message handling (at stack, card or control level)
<lang LiveCode>on keyDown k
<syntaxhighlight lang="livecode">on keyDown k
-- do stuff, keycode is held in k
-- do stuff, keycode is held in k
if k is not 46 then pass keyDown // will be trapped if "." is pressed, others will be passed on through the message path
if k is not 46 then pass keyDown // will be trapped if "." is pressed, others will be passed on through the message path
end keyDown</lang>
end keyDown</syntaxhighlight>
You can substitute keyUp, rawKeyUp, rawKeyDown for keyUp in above. The non-raw handlers do not readily cope with special key presses, and they have their own handlers such as escapeKey, enterKey, altkey, commandKey... look up "key" in the LC dictionary to find more.
You can substitute keyUp, rawKeyUp, rawKeyDown for keyUp in above. The non-raw handlers do not readily cope with special key presses, and they have their own handlers such as escapeKey, enterKey, altkey, commandKey... look up "key" in the LC dictionary to find more.


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>if key? [make "keyhit readchar]</lang>
<syntaxhighlight lang="logo">if key? [make "keyhit readchar]</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
===Without delay===
===Without delay===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
k$=inkey$
k$=inkey$
</syntaxhighlight>
</lang>


===Using delay===
===Using delay===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
K$=""
K$=""
If Inkey(2000)<>-1 then k$=Key$
If Inkey(2000)<>-1 then k$=Key$
Print k$
Print k$
</syntaxhighlight>
</lang>


===Check specific key===
===Check specific key===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
k$=""
k$=""
If keypress(32) then k$=" "
If keypress(32) then k$=" "
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This will create a little panel, once the panel has focus the keys are captured and displayed inside the panel.
This will create a little panel, once the panel has focus the keys are captured and displayed inside the panel.
<lang Mathematica>i = {};
<syntaxhighlight lang="mathematica">i = {};
EventHandler[Panel[Dynamic[i],
EventHandler[Panel[Dynamic[i],
ImageSize -> {300, 300}], {"KeyDown" :>
ImageSize -> {300, 300}], {"KeyDown" :>
AppendTo[i, CurrentValue["EventKey"]]}]</lang>
AppendTo[i, CurrentValue["EventKey"]]}]</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
{{works with|Mini Micro}}
{{works with|Mini Micro}}
<lang MiniScript>x = key.available</lang>
<syntaxhighlight lang="miniscript">x = key.available</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 1,092: Line 1,092:
Using https://github.com/johnnovak/illwill
Using https://github.com/johnnovak/illwill


<lang nim>import os, illwill
<syntaxhighlight lang="nim">import os, illwill


illwillInit(fullscreen=false)
illwillInit(fullscreen=false)
Line 1,107: Line 1,107:
sleep(1000)
sleep(1000)
</syntaxhighlight>
</lang>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>import: console
<syntaxhighlight lang="oforth">import: console


: checkKey
: checkKey
Line 1,116: Line 1,116:
System.Console receiveTimeout(2000000) ->key // Wait a key pressed for 2 seconds
System.Console receiveTimeout(2000000) ->key // Wait a key pressed for 2 seconds
key ifNotNull: [ System.Out "Key pressed : " << key << cr ]
key ifNotNull: [ System.Out "Key pressed : " << key << cr ]
"Done" println ; </lang>
"Done" println ; </syntaxhighlight>


Other options :
Other options :
<lang Oforth>System.Console receive ->key // Wait until a key is pressed ( = receiveTimeout(null) )
<syntaxhighlight lang="oforth">System.Console receive ->key // Wait until a key is pressed ( = receiveTimeout(null) )
System.Console receiveChar ->aChar // Wait until a character is pressed. All other keys are ignored
System.Console receiveChar ->aChar // Wait until a character is pressed. All other keys are ignored
System.Console receiveTimeout(0) ->key // Check if a key is pressed and return immediatly</lang>
System.Console receiveTimeout(0) ->key // Check if a key is pressed and return immediatly</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use strict;
use warnings;
use warnings;
Line 1,135: Line 1,135:
}
}
print "got key '$key'\n";
print "got key '$key'\n";
ReadMode('restore');</lang>
ReadMode('restore');</syntaxhighlight>


In many cases one does not want to wait for each step end. In this case you can use two parallel processes:
In many cases one does not want to wait for each step end. In this case you can use two parallel processes:
<lang perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use strict;
use warnings;
use warnings;
Line 1,187: Line 1,187:
}
}
ReadMode('restore');
ReadMode('restore');
}</lang>
}</syntaxhighlight>


This code prints <code>"doing something"</code> 10 times and then ends. Parallelly another process prints every key you type in.
This code prints <code>"doing something"</code> 10 times and then ends. Parallelly another process prints every key you type in.


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- if key was not pressed get_key() returns -1</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- if key was not pressed get_key() returns -1</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


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


=={{header|Plain English}}==
=={{header|Plain English}}==
Print the numeric value of any key pressed without waiting.
Print the numeric value of any key pressed without waiting.
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Handle any events.
Handle any events.
Line 1,218: Line 1,218:
Put the event's key into a key.
Put the event's key into a key.
Write "" then the key to the console.
Write "" then the key to the console.
If the key is the escape key, relinquish control.</lang>
If the key is the escape key, relinquish control.</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
The following uses the special <code>$Host</code> variable which points to an instance of the PowerShell host application. Since the host's capabilities may vary this may not work in all PowerShell hosts. In particular, this works in the console host, but not in the PowerShell ISE.
The following uses the special <code>$Host</code> variable which points to an instance of the PowerShell host application. Since the host's capabilities may vary this may not work 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) {
<syntaxhighlight lang="powershell">if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey()
$key = $Host.UI.RawUI.ReadKey()
}</lang>
}</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Line 1,230: Line 1,230:


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>
<syntaxhighlight lang="purebasic">k$ = Inkey()</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
from __future__ import absolute_import, division, unicode_literals, print_function
Line 1,284: Line 1,284:
if __name__ == "__main__":
if __name__ == "__main__":
main()
main()
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 1,290: Line 1,290:
Using <tt>stty</tt> to get the terminal into raw mode.
Using <tt>stty</tt> to get the terminal into raw mode.


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define-syntax-rule (with-raw body ...)
(define-syntax-rule (with-raw body ...)
Line 1,306: Line 1,306:
(printf "You pressed ~a\n" (read-char))
(printf "You pressed ~a\n" (read-char))
(printf "You didn't press a key\n")))
(printf "You didn't press a key\n")))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,312: Line 1,312:
{{works with|Rakudo|2018.10}}
{{works with|Rakudo|2018.10}}


<lang perl6>use Term::ReadKey;
<syntaxhighlight lang="raku" line>use Term::ReadKey;


react {
react {
Line 1,321: Line 1,321:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,329: Line 1,329:
:::* PC/REXX
:::* PC/REXX
:::* Personal REXX
:::* Personal REXX
<lang rexx>/*REXX program demonstrates if any key has been presssed. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates if any key has been presssed. */


Line 1,337: Line 1,337:
∙</lang>
∙</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
if getchar() see "A key was pressed" + nl
if getchar() see "A key was pressed" + nl
else see "No key was pressed" + nl ok
else see "No key was pressed" + nl ok
</syntaxhighlight>
</lang>


=={{header|Robotic}}==
=={{header|Robotic}}==
<lang robotic>
<syntaxhighlight lang="robotic">
: "loop"
: "loop"
if "KEY_PRESSED" != 0 then "#store"
if "KEY_PRESSED" != 0 then "#store"
Line 1,355: Line 1,355:
set "storedKey" to "KEY_PRESSED"
set "storedKey" to "KEY_PRESSED"
goto "#return"
goto "#return"
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>
<syntaxhighlight lang="ruby">
begin
begin
check = STDIN.read_nonblock(1)
check = STDIN.read_nonblock(1)
Line 1,366: Line 1,366:


puts check if check
puts check if check
</syntaxhighlight>
</lang>
Test in unix shell:
Test in unix shell:
<lang bash>
<syntaxhighlight lang="bash">
% ruby keypress_check.rb
% ruby keypress_check.rb
% echo -n y | ruby keypress_check.rb
% echo -n y | ruby keypress_check.rb
y
y
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>import java.awt.event.{KeyAdapter, KeyEvent}
<syntaxhighlight lang="scala">import java.awt.event.{KeyAdapter, KeyEvent}


import javax.swing.{JFrame, SwingUtilities}
import javax.swing.{JFrame, SwingUtilities}
Line 1,407: Line 1,407:
foo()
foo()
})
})
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Line 1,414: Line 1,414:
the function [http://seed7.sourceforge.net/libraries/keybd.htm#keypressed%28in_keyboard_file%29 keypressed],
the function [http://seed7.sourceforge.net/libraries/keybd.htm#keypressed%28in_keyboard_file%29 keypressed],
which can be used to determine if a key has been pressed.
which can be used to determine if a key has been pressed.
<lang seed7>if keypressed(KEYBOARD) then
<syntaxhighlight lang="seed7">if keypressed(KEYBOARD) then
writeln("A key was pressed");
writeln("A key was pressed");
else
else
writeln("No key was pressed");
writeln("No key was pressed");
end if;</lang>
end if;</syntaxhighlight>


=={{header|Tcl}}==
=={{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:
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
<syntaxhighlight lang="tcl">fconfigure stdin -blocking 0
set ch [read stdin 1]
set ch [read stdin 1]
fconfigure stdin -blocking 1
fconfigure stdin -blocking 1
Line 1,430: Line 1,430:
} else {
} else {
# Got the character $ch
# Got the character $ch
}</lang>
}</syntaxhighlight>
The second method is to set up an event listener to perform callbacks when there is at least one character available:
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
<syntaxhighlight lang="tcl">fileevent stdin readable GetChar
proc GetChar {} {
proc GetChar {} {
set ch [read stdin 1]
set ch [read stdin 1]
Line 1,441: Line 1,441:
}
}


vwait forever; # run the event loop if necessary</lang>
vwait forever; # run the event loop if necessary</syntaxhighlight>
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.
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.


=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
TI-83 BASIC has a built in getKey function.
TI-83 BASIC has a built in getKey function.
<lang ti83b>
<syntaxhighlight lang="ti83b">
:getKey→G
:getKey→G
</syntaxhighlight>
</lang>
This returns the key code of the key pressed which is the row number followed by the column number. The left up and down arrow keys are grouped with row 2 as 24, 25, and 26, and the down arrow key is grouped with row 3 as 34.
This returns the key code of the key pressed which is the row number followed by the column number. The left up and down arrow keys are grouped with row 2 as 24, 25, and 26, and the down arrow key is grouped with row 3 as 34.


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
This returns the key code of the key pressed.
This returns the key code of the key pressed.
<lang Wee Basic>let keycode=0
<syntaxhighlight lang="wee basic">let keycode=0
print 1 "Press any key and its key code will appear."
print 1 "Press any key and its key code will appear."
while keycode=0
while keycode=0
Line 1,459: Line 1,459:
wend
wend
print 1 keycode
print 1 keycode
end</lang>
end</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "scheduler" for Scheduler
<syntaxhighlight lang="ecmascript">import "scheduler" for Scheduler
import "timer" for Timer
import "timer" for Timer
import "io" for Stdin, Stdout
import "io" for Stdin, Stdout
Line 1,483: Line 1,483:
}
}


Stdin.isRaw = false</lang>
Stdin.isRaw = false</syntaxhighlight>


{{out}}
{{out}}
Line 1,493: Line 1,493:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int K, N;
int K, N;
[N:= 0;
[N:= 0;
Line 1,500: Line 1,500:
N:= N+1;
N:= N+1;
until K;
until K;
]</lang>
]</syntaxhighlight>


{{omit from|ACL2}}
{{omit from|ACL2}}