Keyboard input/Keypress check: Difference between revisions
m
Use inputReady instead of the deprecated function keypress
Thundergnat (talk | contribs) (Rename Perl 6 -> Raku, alphabetize, minor clean-up) |
m (Use inputReady instead of the deprecated function keypress) |
||
(22 intermediate revisions by 16 users not shown) | |||
Line 6:
If no key has been pressed, the program should continue without waiting.
<br><br>
=={{header|6502 Assembly}}==
{{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.
<syntaxhighlight lang="6502asm">define sysLastKey $ff
main:
jsr getKeyPress
;put the rest of your program here.
jsr delay
jmp main
getKeyPress:
lda $ff
sta $00
rts
delay:
nop
nop
dex
bne delay
rts</syntaxhighlight>
{{out}}
<pre>
Pressing various keys results in the following:
0000: 73 ;lower case "s"
0000: 31 ;"1"
0000: 20 ;spacebar
</pre>
=={{header|Action!}}==
The KEY variable returns the key code, or 255 if no key was pressed.
<syntaxhighlight lang="action">Proc Main()
Byte KEY,k=764
KEY=K
Return</syntaxhighlight>
=={{header|Ada}}==
<
Available : Boolean;
Ada.Text_IO.Get_Immediate (Ch, Available);</
If key was pressed, Available is set to True and Ch contains the value.
If not, Available is set to False.
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!
<syntaxhighlight lang="amazing hopper">
#include <flow.h>
DEF-MAIN(argv, argc)
BREAK-ON
SET(c,0)
WHILE (1)
COND( KEY-PRESSED? )
SCAN-CODE(c)
BREAK-IF ( c ) IS-ESCAPE
CEND
PRNL( "CODE = ", c )
WEND
PRNL( "Last key pressed: ", c )
END
</syntaxhighlight>
{{out}}
<pre>
CODE = 0
:
CODE = 100
:
Last key pressed: 27
$
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* Programme assembleur ARM Raspberry */
Line 416 ⟶ 481:
bx lr @return
</syntaxhighlight>
=={{header|AutoHotkey}}==
Waits for the user to type a string (not supported on Windows 9x: it does nothing).
<
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds</
Checks if a keyboard key or mouse/joystick button is down or up. Also retrieves joystick status.
<
GetKeyState, State, RButton ; Right mouse button.</
Function version of GetKeyState.
<
State := GetKeyState("RButton", "P") ; Right mouse button. P = Physical state.</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: TAWK -f KEYBOARD_INPUT_KEYPRESS_CHECK.AWK
BEGIN {
Line 454 ⟶ 519:
exit(0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 464 ⟶ 529:
=={{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.
<syntaxhighlight lang
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="applesoftbasic">K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K)</syntaxhighlight>
==={{header|BaCon}}===
<
PRINT "Press <escape> to exit now..."
key = GETKEY
IF key = 27 THEN
END
END IF</
==={{header|
<syntaxhighlight lang="freebasic">do
k$ = key
until k$ <> ""
if length(k$) = 2 then
print "The key pressed was "; k$; " (ascii "; chr(k$); ")"
else
print "An extended key was pressed"
end if</syntaxhighlight>
==={{header|BBC BASIC}}===
<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:
<syntaxhighlight lang="bbcbasic"> key% = INKEY(0)</syntaxhighlight>
==={{header|IS-BASIC}}===
<
or
<syntaxhighlight lang
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">DO: k$ = INKEY$: LOOP UNTIL k$ <> ""
PRINT k$</syntaxhighlight>
==={{header|Yabasic}}===
<code>inkey$</code> interrupts (halt) the flow of the program until a key is pressed.
<code>inkey$</code> may only be used, if <code>clear screen</code> has been called at least once.
<syntaxhighlight lang="yabasic">clear screen
k$ = inkey$</syntaxhighlight>
==={{header|ZX Spectrum Basic}}===
{{works with|Locomotive Basic}}
<
20 LET k$ = INKEY$</
=={{header|C}}==
For POSIX systems. Ctrl-C to stop:<
#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 <fcntl.h>
Line 540 ⟶ 628:
while(1) {
set_mode(1);
/* force C library buffers to be written to kernel buffers,
and flush pending input to avoid previously pressed keys */
fflush(stdout);
while (!(c = get_key())) usleep(10000);
printf("key %d\n", c);
}
}</
=={{header|Common Lisp}}==
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<syntaxhighlight lang="lisp">(defun keypress-check ()
(with-screen (scr :input-echoing nil :input-blocking nil :input-buffering nil :enable-function-keys t)
(loop
;; Determine if a key has been pressed ...
(if (key-pressed-p scr)
;; ... and store this in a variable.
(let ((ch (get-char scr)))
;; exit the loop by pressing q.
(if (eql (code-char ch) #\q)
(return)
(princ (code-char ch) scr)))
(progn
;; If no key has been pressed, the program should continue without waiting.
(princ #\. scr)
(refresh scr)
;; we wait anyway to spare the CPU.
(sleep 0.15))))))</syntaxhighlight>
=={{header|C sharp|C#}}==
<
if(Console.KeyAvailable)
chr = Console.ReadKey().Key.ToString();</
=={{header|Clojure}}==
Line 557 ⟶ 669:
<pre>$ lein trampoline run</pre>
<
(ns keypress.core
(:import jline.Terminal)
Line 574 ⟶ 686:
(prompt)
(shutdown-agents))
</syntaxhighlight>
=={{header|D}}==
<
void _STI_conio();
void _STD_conio();
Line 592 ⟶ 704:
_STD_conio();
}</
=={{header|Delphi}}==
This is valid for a GUI application!
<
interface
Line 623 ⟶ 735:
end;
end.</
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<
public program()
Line 637 ⟶ 749:
chr := console.readChar()
}
}</
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
!$KEY
.........
GET(K$)
.........
</syntaxhighlight>
Note: If no key was pressed K$ is empty string "".
=={{header|Euphoria}}==
<
key = get_key() -- if key was not pressed get_key() returns -1</
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<
let chr = if Console.KeyAvailable then Console.ReadKey().Key.ToString() else String.Empty</
=={{header|Forth}}==
<
: check key? if key last-key ! then ;</
=={{header|FreeBASIC}}==
<
Dim k As String
Line 676 ⟶ 788:
End If
Sleep</
Sample input/output
Line 684 ⟶ 796:
The key pressed was A (ascii 65)
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
void local fn BuildWindow
subclass window _window, @"Keyboard input/Keypress check"
text,24
print %(180,190)@"Press any key"
end fn
void local fn DoDialog( ev as long, tag as long )
select ( ev )
case _windowKeyDown
select ( tag )
case _window
cls : printf %(180,190)@"\"%@\" key pressed",fn EventCharacters
DialogEventSetBool( YES )// we handled
end select
end select
end fn
fn BuildWindow
on dialog fn DoDialog
HandleEvents
</syntaxhighlight>
=={{header|Gambas}}==
<
'Requires a TextBox or similar on the Form to work
Print Key.Text;
End</
Output:
<pre>
Line 699 ⟶ 839:
=={{header|Go}}==
{{libheader|Curses}}
<
import (
Line 721 ⟶ 861:
s.Refresh()
time.Sleep(500 * time.Millisecond)
}</
s.Println()
Line 741 ⟶ 881:
s.GetChar()
You don't need external dependencies to achieve this. You can use a channel and set a timeout on it.
::<
// stackoverflow.com/questions/43965556/how-to-read-a-key-in-go-but-continue-application-if-no-key-pressed-within-x-seco
import (
Line 771 ⟶ 911:
fmt.Println("Time out!")
}
}</
=={{header|Haskell}}==
<
import Control.Monad
import Data.Maybe
Line 793 ⟶ 933:
else putStrLn "Awaiting char.." >>
threadDelay 500000 >> wait c
</syntaxhighlight>
Output:
<pre>
Line 804 ⟶ 944:
=={{header|Icon}} and {{header|Unicon}}==
<
delay(1000) # give user a chance to input
if kbhit() then # test for input
Line 810 ⟶ 950:
else # use getche for echo
write("No input waiting")
end</
=={{header|J}}==
(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}}</syntaxhighlight>
=={{header|Java}}==
{{works with|java|8}}
<
import javax.swing.*;
Line 836 ⟶ 981:
});
}
}</
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
let thePressedKey;
function handleKey(evt) {
thePressedKey = evt;
console.log(thePressedKey);
}
document.addEventListener('keydown', handleKey);
</syntaxhighlight>
=={{header|Julia}}==
<
function keypresswindow()
Line 860 ⟶ 1,017:
keypresswindow()
</syntaxhighlight>
=={{header|Kotlin}}==
Translated from the Java entry but then modified so as to quit the program when the Enter key is pressed:
<
import java.awt.event.KeyAdapter
Line 894 ⟶ 1,051:
f.isVisible = true
}
}</
=={{header|Lingo}}==
<
-- event handler
Line 903 ⟶ 1,060:
pressedKey = _key.key
put "A key was pressed:" && pressedKey
end</
=={{header|LiveCode}}==
Line 909 ⟶ 1,066:
Example
<
-- exit loop if "." or the escapeKey is pressed
if 46 is in the keysDown or 65307 is in the keysdown then
Line 918 ⟶ 1,075:
wait 200 millisec
end if
end repeat</
Example of event message handling (at stack, card or control level)
<
-- 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
end keyDown</
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|M2000 Interpreter}}==
===Without delay===
<syntaxhighlight lang="m2000 interpreter">
k$=inkey$
</syntaxhighlight>
===Using delay===
<syntaxhighlight lang="m2000 interpreter">
K$=""
If Inkey(2000)<>-1 then k$=Key$
Print k$
</syntaxhighlight>
===Check specific key===
<syntaxhighlight lang="m2000 interpreter">
k$=""
If keypress(32) then k$=" "
</syntaxhighlight>
=={{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.
<syntaxhighlight lang="mathematica">i = {};
EventHandler[Panel[Dynamic[i],
ImageSize -> {300, 300}], {"KeyDown" :>
AppendTo[i, CurrentValue["EventKey"]]}]</syntaxhighlight>
=={{header|MiniScript}}==
{{works with|Mini Micro}}
<
=={{header|Nim}}==
Using https://github.com/johnnovak/illwill
<syntaxhighlight lang="nim">import os, illwill
illwillInit(fullscreen=false)
while true:
var key = getKey()
case key
of Key.None:
echo "not received a key, I can do other stuff here"
of Key.Escape, Key.Q:
break
else:
echo "Key pressed: ", $key
sleep(1000)
</syntaxhighlight>
=={{header|Oforth}}==
<
: checkKey
Line 959 ⟶ 1,144:
System.Console receiveTimeout(2000000) ->key // Wait a key pressed for 2 seconds
key ifNotNull: [ System.Out "Key pressed : " << key << cr ]
"Done" println ; </
Other options :
<
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</
=={{header|Perl}}==
<
use strict;
use warnings;
Line 978 ⟶ 1,163:
}
print "got key '$key'\n";
ReadMode('restore');</
In many cases one does not want to wait for each step end. In this case you can use two parallel processes:
<
use strict;
use warnings;
Line 1,030 ⟶ 1,215:
}
ReadMode('restore');
}</
This code prints <code>"doing something"</code> 10 times and then ends. Parallelly another process prints every key you type in.
=={{header|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>
<!--</syntaxhighlight>-->
=={{header|PicoLisp}}==
<syntaxhighlight lang
=={{header|Plain English}}==
Print the numeric value of any key pressed without waiting.
<syntaxhighlight lang="plainenglish">To run:
Start up.
Handle any events.
Shut down.
To handle any events:
Deque an event.
If the event is nil, exit.
Handle the event.
Repeat.
To handle an event:
If the event's kind is "key down", handle the event (key down).
To handle an event (key down):
Put the event's key into a key.
Write "" then the key to the console.
If the key is the escape key, relinquish control.</syntaxhighlight>
=={{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.
<
$key = $Host.UI.RawUI.ReadKey()
}</
=={{header|PureBasic}}==
Line 1,050 ⟶ 1,258:
If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey().
<
=={{header|Python}}==
<
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
Line 1,104 ⟶ 1,312:
if __name__ == "__main__":
main()
</syntaxhighlight>
=={{header|Racket}}==
Line 1,110 ⟶ 1,318:
Using <tt>stty</tt> to get the terminal into raw mode.
<
#lang racket
(define-syntax-rule (with-raw body ...)
Line 1,126 ⟶ 1,334:
(printf "You pressed ~a\n" (read-char))
(printf "You didn't press a key\n")))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,132 ⟶ 1,340:
{{works with|Rakudo|2018.10}}
<syntaxhighlight lang="raku"
react {
Line 1,141 ⟶ 1,349:
}
}
}</
=={{header|REXX}}==
Line 1,149 ⟶ 1,357:
:::* PC/REXX
:::* Personal REXX
<
∙
Line 1,157 ⟶ 1,365:
∙
∙
∙</
=={{header|Ring}}==
<
if getchar() see "A key was pressed" + nl
else see "No key was pressed" + nl ok
</syntaxhighlight>
=={{header|Robotic}}==
<
: "loop"
if "KEY_PRESSED" != 0 then "#store"
Line 1,175 ⟶ 1,383:
set "storedKey" to "KEY_PRESSED"
goto "#return"
</syntaxhighlight>
=={{header|RPL}}==
≪ '''IF''' KEY '''THEN''' 'Entry' STO '''END''' ≫
If no key is pressed and the <code>Entry</code> variable does not exist yet, it won't be created.
=={{header|Ruby}}==
<
begin
check = STDIN.read_nonblock(1)
Line 1,186 ⟶ 1,398:
puts check if check
</syntaxhighlight>
Test in unix shell:
<
% ruby keypress_check.rb
% echo -n y | ruby keypress_check.rb
y
</syntaxhighlight>
=={{header|Scala}}==
<
import javax.swing.{JFrame, SwingUtilities}
Line 1,227 ⟶ 1,439:
foo()
})
}</
=={{header|Seed7}}==
The library [http://seed7.sourceforge.net/libraries/keybd.htm keybd.s7i] defines
the file [http://seed7.sourceforge.net/libraries/keybd.htm#KEYBOARD KEYBOARD] and
the function [http://seed7.sourceforge.net/libraries/keybd.htm#
which can be used to determine if a key has been pressed.
<
writeln("A key was pressed");
else
writeln("No key was pressed");
end if;</
=={{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:
<
set ch [read stdin 1]
fconfigure stdin -blocking 1
Line 1,250 ⟶ 1,462:
} else {
# Got the character $ch
}</
The second method is to set up an event listener to perform callbacks when there is at least one character available:
<
proc GetChar {} {
set ch [read stdin 1]
Line 1,261 ⟶ 1,473:
}
vwait forever; # run the event loop if necessary</
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}}==
TI-83 BASIC has a built in getKey function.
<
:getKey→G
</syntaxhighlight>
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}}==
This returns the key code of the key pressed.
<
print 1 "Press any key and its key code will appear."
while keycode=0
Line 1,279 ⟶ 1,491:
wend
print 1 keycode
end</
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "scheduler" for Scheduler
import "timer" for Timer
import "io" for Stdin, Stdout
Stdin.isRaw = true // no echoing or buffering
var b
Scheduler.add {
b = Stdin.readByte()
}
System.print("Awaiting keypress..")
Timer.sleep(2000) // allow 2 seconds say
if (b) {
System.write("The key with code %(b) was pressed")
System.print((b > 31 && b < 127) ? " namely '%(String.fromByte(b))'." : ".")
} else {
System.print("No key was pressed, carrying on...")
}
Stdin.isRaw = false</syntaxhighlight>
{{out}}
Sample session when 'a' key pressed.
<pre>
Awaiting keypress..
The key with code 97 was pressed namely 'a'.
</pre>
=={{header|XPL0}}==
<
int K, N;
[N:= 0;
Line 1,289 ⟶ 1,532:
N:= N+1;
until K;
]</
{{omit from|ACL2}}
|