Keyboard input/Keypress check: Difference between revisions

m
Use inputReady instead of the deprecated function keypress
No edit summary
m (Use inputReady instead of the deprecated function keypress)
 
(9 intermediate revisions by 6 users not shown)
Line 9:
{{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.
<langsyntaxhighlight lang="6502asm">define sysLastKey $ff
 
main:
Line 28:
dex
bne delay
rts</langsyntaxhighlight>
{{out}}
<pre>
Line 39:
=={{header|Action!}}==
The KEY variable returns the key code, or 255 if no key was pressed.
<langsyntaxhighlight Actionlang="action">Proc Main()
Byte KEY,k=764
KEY=K
Return</langsyntaxhighlight>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">Ch : Character;
Available : Boolean;
 
Ada.Text_IO.Get_Immediate (Ch, Available);</langsyntaxhighlight>
 
If key was pressed, Available is set to True and Ch contains the value.
Line 56:
=={{header|Amazing Hopper}}==
Version: hopper-FLOW!
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <flow.h>
 
Line 71:
PRNL( "Last key pressed: ", c )
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 84:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* Programme assembleur ARM Raspberry */
Line 481:
bx lr @return
 
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
Waits for the user to type a string (not supported on Windows 9x: it does nothing).
<langsyntaxhighlight AutoHotkeylang="autohotkey">; Input [, OutputVar, Options, EndKeys, MatchList]
Input, KeyPressed, L1 T2 ; Length = 1, Timeout = 2 seconds</langsyntaxhighlight>
 
 
Checks if a keyboard key or mouse/joystick button is down or up. Also retrieves joystick status.
<langsyntaxhighlight AutoHotkeylang="autohotkey">; GetKeyState, OutputVar, KeyName [, Mode]
GetKeyState, State, RButton ; Right mouse button.</langsyntaxhighlight>
 
 
Function version of GetKeyState.
<langsyntaxhighlight AutoHotkeylang="autohotkey">; KeyIsDown := GetKeyState("KeyName" [, "Mode"])
State := GetKeyState("RButton", "P") ; Right mouse button. P = Physical state.</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: TAWK -f KEYBOARD_INPUT_KEYPRESS_CHECK.AWK
BEGIN {
Line 519:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 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 ="axe">getKey→K</langsyntaxhighlight>
 
=={{header|BASIC}}==
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K)</langsyntaxhighlight>
 
==={{header|BaCon}}===
<langsyntaxhighlight lang="freebasic">
PRINT "Press <escape> to exit now..."
key = GETKEY
IF key = 27 THEN
END
END IF</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="freebasic">do
k$ = key
until k$ <> ""
Line 553:
else
print "An extended key was pressed"
end if</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> key$ = INKEY$(0)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="bbcbasic"> key% = INKEY(0)</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 LET K$=INKEY$</langsyntaxhighlight>
 
or
 
<syntaxhighlight lang IS="is-BASICbasic">100 GET K$</langsyntaxhighlight>
 
==={{header|QBasic}}===
<langsyntaxhighlight QBasiclang="qbasic">DO: k$ = INKEY$: LOOP UNTIL k$ <> ""
PRINT k$</langsyntaxhighlight>
 
==={{header|Yabasic}}===
Line 575:
 
<code>inkey$</code> may only be used, if <code>clear screen</code> has been called at least once.
<langsyntaxhighlight lang="yabasic">clear screen
k$ = inkey$</langsyntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
{{works with|Locomotive Basic}}
 
<langsyntaxhighlight lang="zxbasic">10 REM k$ will be empty, if no key has been pressed
20 LET k$ = INKEY$</langsyntaxhighlight>
 
 
=={{header|C}}==
For POSIX systems. Ctrl-C to stop:<langsyntaxhighlight Clang="c">#include <stdio.h>
#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>
#include <fcntl.h>
 
Line 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);
}
}</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
==={{header|ncurses}}===
To interface the ncurses C library from Lisp, the ''croatoan'' library is used.
<langsyntaxhighlight lang="lisp">(defun keypress-check ()
(with-screen (scr :input-echoing nil :input-blocking nil :input-buffering nil :enable-function-keys t)
(loop
Line 652 ⟶ 655:
(refresh scr)
;; we wait anyway to spare the CPU.
(sleep 0.15))))))</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">string chr = string.Empty;
if(Console.KeyAvailable)
chr = Console.ReadKey().Key.ToString();</langsyntaxhighlight>
 
=={{header|Clojure}}==
Line 666 ⟶ 669:
<pre>$ lein trampoline run</pre>
 
<langsyntaxhighlight lang="clojure">
(ns keypress.core
(:import jline.Terminal)
Line 683 ⟶ 686:
(prompt)
(shutdown-agents))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">extern (C) {
void _STI_conio();
void _STD_conio();
Line 701 ⟶ 704:
 
_STD_conio();
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
This is valid for a GUI application!
<langsyntaxhighlight Delphilang="delphi">unit Unit1;
 
interface
Line 732 ⟶ 735:
end;
 
end.</langsyntaxhighlight>
 
=={{header|Elena}}==
{{trans|C#}}
ELENA 4.x :
<langsyntaxhighlight lang="elena">import extensions;
 
public program()
Line 746 ⟶ 749:
chr := console.readChar()
}
}</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
!$KEY
.........
GET(K$)
.........
</syntaxhighlight>
</lang>
Note: If no key was pressed K$ is empty string "".
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">integer key
key = get_key() -- if key was not pressed get_key() returns -1</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<langsyntaxhighlight lang="fsharp">open System;
 
let chr = if Console.KeyAvailable then Console.ReadKey().Key.ToString() else String.Empty</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">variable last-key
: check key? if key last-key ! then ;</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim k As String
Line 785 ⟶ 788:
End If
 
Sleep</langsyntaxhighlight>
 
Sample input/output
Line 793 ⟶ 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}}==
<langsyntaxhighlight lang="gambas">Public Sub Form_KeyPress()
 
'Requires a TextBox or similar on the Form to work
Print Key.Text;
 
End</langsyntaxhighlight>
Output:
<pre>
Line 808 ⟶ 839:
=={{header|Go}}==
{{libheader|Curses}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 830 ⟶ 861:
s.Refresh()
time.Sleep(500 * time.Millisecond)
}</langsyntaxhighlight>
 
s.Println()
Line 850 ⟶ 881:
s.GetChar()
You don't need external dependencies to achieve this. You can use a channel and set a timeout on it.
::<langsyntaxhighlight 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
import (
Line 880 ⟶ 911:
fmt.Println("Time out!")
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Concurrent
import Control.Monad
import Data.Maybe
Line 902 ⟶ 933:
else putStrLn "Awaiting char.." >>
threadDelay 500000 >> wait c
</syntaxhighlight>
</lang>
Output:
<pre>
Line 913 ⟶ 944:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
delay(1000) # give user a chance to input
if kbhit() then # test for input
Line 919 ⟶ 950:
else # use getche for echo
write("No input waiting")
end</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="java">import java.awt.event.*;
import javax.swing.*;
 
Line 945 ⟶ 981:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
<lang javaScript>
let thePressedKey;
 
Line 957 ⟶ 993:
 
document.addEventListener('keydown', handleKey);
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">using Gtk
 
function keypresswindow()
Line 981 ⟶ 1,017:
 
keypresswindow()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Translated from the Java entry but then modified so as to quit the program when the Enter key is pressed:
<langsyntaxhighlight lang="scala">// version 1.1
 
import java.awt.event.KeyAdapter
Line 1,015 ⟶ 1,051:
f.isVisible = true
}
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- in some movie script
 
-- event handler
Line 1,024 ⟶ 1,060:
pressedKey = _key.key
put "A key was pressed:" && pressedKey
end</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Line 1,030 ⟶ 1,066:
 
Example
<langsyntaxhighlight LiveCodelang="livecode">repeat 100 times
-- exit loop if "." or the escapeKey is pressed
if 46 is in the keysDown or 65307 is in the keysdown then
Line 1,039 ⟶ 1,075:
wait 200 millisec
end if
end repeat</langsyntaxhighlight>
Example of event message handling (at stack, card or control level)
<langsyntaxhighlight LiveCodelang="livecode">on keyDown 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
end keyDown</langsyntaxhighlight>
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}}==
<langsyntaxhighlight lang="logo">if key? [make "keyhit readchar]</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Without delay===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
k$=inkey$
</syntaxhighlight>
</lang>
 
===Using delay===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
K$=""
If Inkey(2000)<>-1 then k$=Key$
Print k$
</syntaxhighlight>
</lang>
 
===Check specific key===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
k$=""
If keypress(32) then k$=" "
</syntaxhighlight>
</lang>
 
=={{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.
<langsyntaxhighlight Mathematicalang="mathematica">i = {};
EventHandler[Panel[Dynamic[i],
ImageSize -> {300, 300}], {"KeyDown" :>
AppendTo[i, CurrentValue["EventKey"]]}]</langsyntaxhighlight>
 
=={{header|MiniScript}}==
{{works with|Mini Micro}}
<langsyntaxhighlight MiniScriptlang="miniscript">x = key.available</langsyntaxhighlight>
 
=={{header|Nim}}==
Line 1,084 ⟶ 1,120:
Using https://github.com/johnnovak/illwill
 
<langsyntaxhighlight lang="nim">import os, illwill
 
illwillInit(fullscreen=false)
Line 1,099 ⟶ 1,135:
sleep(1000)
</syntaxhighlight>
</lang>
 
=={{header|Oforth}}==
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: checkKey
Line 1,108 ⟶ 1,144:
System.Console receiveTimeout(2000000) ->key // Wait a key pressed for 2 seconds
key ifNotNull: [ System.Out "Key pressed : " << key << cr ]
"Done" println ; </langsyntaxhighlight>
 
Other options :
<langsyntaxhighlight Oforthlang="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 receiveTimeout(0) ->key // Check if a key is pressed and return immediatly</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
Line 1,127 ⟶ 1,163:
}
print "got key '$key'\n";
ReadMode('restore');</langsyntaxhighlight>
 
In many cases one does not want to wait for each step end. In this case you can use two parallel processes:
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use warnings;
Line 1,179 ⟶ 1,215:
}
ReadMode('restore');
}</langsyntaxhighlight>
 
This code prints <code>"doing something"</code> 10 times and then ends. Parallelly another process prints every key you type in.
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
<!--</langsyntaxhighlight>-->
 
=={{header|PicoLisp}}==
<syntaxhighlight lang PicoLisp="picolisp">(setq *LastKey (key))</langsyntaxhighlight>
 
=={{header|Plain English}}==
Print the numeric value of any key pressed without waiting.
<langsyntaxhighlight lang="plainenglish">To run:
Start up.
Handle any events.
Line 1,210 ⟶ 1,246:
Put the event's key into a key.
Write "" then the key to the console.
If the key is the escape key, relinquish control.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="powershell">if ($Host.UI.RawUI.KeyAvailable) {
$key = $Host.UI.RawUI.ReadKey()
}</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Line 1,222 ⟶ 1,258:
 
If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey().
<langsyntaxhighlight PureBasiclang="purebasic">k$ = Inkey()</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
Line 1,276 ⟶ 1,312:
if __name__ == "__main__":
main()
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 1,282 ⟶ 1,318:
Using <tt>stty</tt> to get the terminal into raw mode.
 
<langsyntaxhighlight lang="racket">
#lang racket
(define-syntax-rule (with-raw body ...)
Line 1,298 ⟶ 1,334:
(printf "You pressed ~a\n" (read-char))
(printf "You didn't press a key\n")))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,304 ⟶ 1,340:
{{works with|Rakudo|2018.10}}
 
<syntaxhighlight lang="raku" perl6line>use Term::ReadKey;
 
react {
Line 1,313 ⟶ 1,349:
}
}
}</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,321 ⟶ 1,357:
:::* PC/REXX
:::* Personal REXX
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates if any key has been presssed. */
 
Line 1,329 ⟶ 1,365:
∙</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
if getchar() see "A key was pressed" + nl
else see "No key was pressed" + nl ok
</syntaxhighlight>
</lang>
 
=={{header|Robotic}}==
<langsyntaxhighlight lang="robotic">
: "loop"
if "KEY_PRESSED" != 0 then "#store"
Line 1,347 ⟶ 1,383:
set "storedKey" to "KEY_PRESSED"
goto "#return"
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="ruby">
begin
check = STDIN.read_nonblock(1)
Line 1,358 ⟶ 1,398:
 
puts check if check
</syntaxhighlight>
</lang>
Test in unix shell:
<langsyntaxhighlight lang="bash">
% ruby keypress_check.rb
% echo -n y | ruby keypress_check.rb
y
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">import java.awt.event.{KeyAdapter, KeyEvent}
 
import javax.swing.{JFrame, SwingUtilities}
Line 1,399 ⟶ 1,439:
foo()
})
}</langsyntaxhighlight>
 
=={{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#keypressed%28in_keyboard_file%29inputReady(in_console_keybd_file) keypressedinputReady],
which can be used to determine if a key has been pressed.
<langsyntaxhighlight lang="seed7">if keypressedinputReady(KEYBOARD) then
writeln("A key was pressed");
else
writeln("No key was pressed");
end if;</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="tcl">fconfigure stdin -blocking 0
set ch [read stdin 1]
fconfigure stdin -blocking 1
Line 1,422 ⟶ 1,462:
} else {
# Got the character $ch
}</langsyntaxhighlight>
The second method is to set up an event listener to perform callbacks when there is at least one character available:
<langsyntaxhighlight lang="tcl">fileevent stdin readable GetChar
proc GetChar {} {
set ch [read stdin 1]
Line 1,433 ⟶ 1,473:
}
 
vwait forever; # run the event loop if necessary</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="ti83b">
: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.
 
=={{header|Wee Basic}}==
This returns the key code of the key pressed.
<langsyntaxhighlight Weelang="wee Basicbasic">let keycode=0
print 1 "Press any key and its key code will appear."
while keycode=0
Line 1,451 ⟶ 1,491:
wend
print 1 keycode
end</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "scheduler" for Scheduler
import "timer" for Timer
import "io" for Stdin, Stdout
Line 1,475 ⟶ 1,515:
}
 
Stdin.isRaw = false</langsyntaxhighlight>
 
{{out}}
Line 1,485 ⟶ 1,525:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int K, N;
[N:= 0;
Line 1,492 ⟶ 1,532:
N:= N+1;
until K;
]</langsyntaxhighlight>
 
{{omit from|ACL2}}
28

edits