Keyboard input/Keypress check: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 398: Line 398:


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





Revision as of 20:52, 5 December 2018

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.

Ada

<lang Ada>Ch : Character; Available : Boolean;

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

If key was pressed, Available is set to True and Ch contains the value. If not, Available is set to False.

AutoHotkey

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


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


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

Axe

Note that while the syntax for getting the most recent keypress is identical to TI-83 BASIC, the keycodes themselves are different. <lang axe>getKey→K</lang>

BASIC

BaCon

<lang freebasic> PRINT "Press <escape> to exit now..." key = GETKEY IF key = 27 THEN

   END

END IF</lang>

Applesoft BASIC

<lang ApplesoftBasic>K = PEEK(-16384) : IF K > 127 THEN POKE -16368,0 : K$ = CHR$(K)</lang>

IS-BASIC

<lang IS-BASIC>100 LET K$=INKEY$</lang>

or

<lang IS-BASIC>100 GET K$</lang>

ZX Spectrum Basic

Works with: Locomotive Basic

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

BBC BASIC

<lang bbcbasic> key$ = INKEY$(0)</lang> 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>

C

For POSIX systems. Ctrl-C to stop:<lang C>#include <stdio.h>

  1. include <termios.h>
  2. include <unistd.h>
  3. include <fcntl.h>

void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; }

tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &new); }

int get_key() { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0;

FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, &tv);

if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; }

int main() { int c; while(1) { set_mode(1); while (!(c = get_key())) usleep(10000); printf("key %d\n", c); } }</lang>

C#

<lang csharp>string chr = string.Empty; if(Console.KeyAvailable)

 chr = Console.ReadKey().Key.ToString();</lang>

Clojure

Library: jline

Note: If you run it with Leiningen, use the special trampoline run to prevent issues:

$ lein trampoline run

<lang clojure> (ns keypress.core

 (:import jline.Terminal)
 (:gen-class))

(def keypress (future (.readCharacter (Terminal/getTerminal) System/in)))

(defn prompt []

 (println "Awaiting char...\n")
 (Thread/sleep 2000)
 (if-not (realized? keypress)
   (recur)
   (println "key: " (char @keypress))))

(defn -main [& args]

 (prompt)
 (shutdown-agents))

</lang>

D

<lang d>extern (C) {

   void _STI_conio();
   void _STD_conio();
   int kbhit();
   int getch();

}

void main() {

   _STI_conio();
   char c;
   if (kbhit())
       c = cast(char)getch();
   _STD_conio();

}</lang>

Delphi

This is valid for a GUI application! <lang Delphi>unit Unit1;

interface

uses

 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs;

type

 TForm1 = class(TForm)
   procedure FormKeyPress(Sender: TObject; var Key: Char);
 private
   SavedPressedKey: Char;
 end;

var

 Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char); begin

 SavedPressedKey := Key;

end;

end.</lang>

Elena

Translation of: C#

ELENA 3.4 : <lang elena>import extensions.

public program [

   auto chr := emptyLiteral.
   if (console isKeyAvailable)
   [
       chr := console readChar
   ]

]</lang>

ERRE

<lang ERRE> !$KEY ......... GET(K$) ......... </lang> Note: If no key was pressed K$ is empty string "".

Euphoria

<lang Euphoria>integer key key = get_key() -- if key was not pressed get_key() returns -1</lang>


F#

Translation of: C#

<lang fsharp>open System;

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

Forth

<lang forth>variable last-key

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

FreeBASIC

<lang freebasic>' FB 1.05.0 Win64

Dim k As String Do

 k = Inkey

Loop Until k <> ""

If Len(k) = 1 Then

 Print "The key pressed was "; k; " (ascii "; Asc(k); ")"

Else

 Print "An extended key was pressed"

End If

Sleep</lang>

Sample input/output

Output:
The key pressed was A (ascii 65)

Gambas

<lang gambas>Public Sub Form_KeyPress()

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

End</lang> Output:

Hello world!

Go

Library: Curses

<lang go>package main

import (

   "log"
   "time"
   gc "code.google.com/p/goncurses"

)

func main() {

   s, err := gc.Init()
   if err != nil {
       log.Fatal("init:", err)
   }
   defer gc.End()
   gc.Cursor(0)
   s.Move(20, 0)
   s.Print("Key check in ")
   for i := 3; i >= 1; i-- {
       s.MovePrint(20, 13, i)
       s.Refresh()
       time.Sleep(500 * time.Millisecond)
   }
   s.Println()
   gc.Echo(false)
   // task requirement next two lines
   s.Timeout(0)
   k := s.GetChar()
   if k == 0 {
       s.Println("No key pressed")
   } else {
       s.Println("You pressed", gc.KeyString(k))
   }
   s.Refresh()
   s.Timeout(-1)
   gc.FlushInput()
   gc.Cursor(1)
   s.GetChar()

}</lang>

Haskell

<lang haskell>import Control.Concurrent import Control.Monad import Data.Maybe import System.IO

main = do

   c <- newEmptyMVar 
   hSetBuffering stdin NoBuffering
   forkIO $ do
     a <- getChar
     putMVar c a
     putStrLn $ "\nChar '" ++ [a] ++
                "' read and stored in MVar"
   wait c
 where wait c = do
         a <- tryTakeMVar c
         if isJust a then return ()
         else putStrLn "Awaiting char.." >>
              threadDelay 500000 >> wait c

</lang> Output:

Awaiting char..
Awaiting char..
Awaiting char..
d
Char 'd' read and stored in MVar

Icon and Unicon

<lang Icon>procedure main()

  delay(1000)                              # give user a chance to input
  if kbhit() then                          # test for input
     write("You entered ",x := getch())    # read w/o echo
  else                                     # use getche for echo
     write("No input waiting")

end</lang>

Java

Works with: java version 8

<lang java>import java.awt.event.*; import javax.swing.*;

public class Test extends JFrame {

   Test() {
       addKeyListener(new KeyAdapter() {
           @Override
           public void keyPressed(KeyEvent e) {
               int keyCode = e.getKeyCode();
               System.out.println(keyCode);
           }
       });
   }
   public static void main(String[] args) {
       SwingUtilities.invokeLater(() -> {
           Test f = new Test();
           f.setFocusable(true);
           f.setVisible(true);
       });
   }

}</lang>

Julia

<lang Julia>using Gtk

function keypresswindow()

   tcount = 0
   txt = "Press a Key"
   win = GtkWindow("Keypress Test", 500, 30) |> (GtkFrame() |> ((vbox = GtkBox(:v)) |> (lab = GtkLabel(txt))))
   function keycall(w, event)
       ch = Char(event.keyval)
       tcount += 1
       set_gtk_property!(lab, :label, "You have typed $tcount chars including $ch this time")
   end
   signal_connect(keycall, win, "key-press-event")
   cond = Condition()
   endit(w) = notify(cond)
   signal_connect(endit, win, :destroy)
   showall(win)
   wait(cond)

end

keypresswindow() </lang>


Kotlin

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

import java.awt.event.KeyAdapter import java.awt.event.KeyEvent import javax.swing.JFrame import javax.swing.SwingUtilities

class Test : JFrame() {

   init {
       println("Press any key to see its code or 'enter' to quit\n")
       addKeyListener(object : KeyAdapter() {
           override fun keyPressed(e: KeyEvent) {
               if (e.keyCode == KeyEvent.VK_ENTER) {
                   isVisible = false
                  dispose()
                  System.exit(0)
               }
               else
                  println(e.keyCode)
           }
       })
   }

}

fun main(args: Array<String>) {

   SwingUtilities.invokeLater {
       val f = Test()
       f.isFocusable = true
       f.isVisible = true
   }

}</lang>

Lingo

<lang lingo>-- in some movie script

-- event handler on keyDown

 pressedKey = _key.key
 put "A key was pressed:" && pressedKey

end</lang>

LiveCode

LiveCode is message based and all stacks, cards and gui controls can have their own keyup/down message handler. You would ordinarily add the relevant event handler to do something when a key is pressed. There is a function however that can be executed that returns a list of keycodes for the keys currently pressed, called keysDown.

Example <lang 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 
       answer "exiting"
       exit repeat
   else
       -- do stuff
       wait 200 millisec
   end if

end repeat</lang> Example of event message handling (at stack, card or control level) <lang 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</lang> 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.

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

M2000 Interpreter

Without delay

<lang M2000 Interpreter> k$=inkey$ </lang>

Using delay

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

Check specific key

<lang M2000 Interpreter> k$="" If keypress(32) then k$=" " </lang>

Oforth

<lang Oforth>import: console

checkKey

| key |

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

Other options : <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 receiveTimeout(0) ->key // Check if a key is pressed and return immediatly</lang>

Perl

<lang perl>#!/usr/bin/perl use strict; use warnings; use Term::ReadKey; ReadMode 4; my $key; until(defined($key = ReadKey(-1))){ # anything sleep 1; } print "got key '$key'\n"; ReadMode('restore');</lang>

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 use strict; use warnings; use Carp; use POSIX; use Term::ReadKey; $| = 1; # don't buffer; stdout is hot now

  1. avoid creation of zombies

sub _cleanup_and_die{ ReadMode('restore'); print "process $$ dying\n"; die; } sub _cleanup_and_exit{ ReadMode('restore'); print "process $$ exiting\n"; exit 1; } $SIG{'__DIE__'} = \&_cleanup_and_die; $SIG{'INT'} = \&_cleanup_and_exit; $SIG{'KILL'} = \&_cleanup_and_exit; $SIG{'TERM'} = \&_cleanup_and_exit; $SIG{__WARN__} = \&_warn;

  1. fork into two processes:
  2. child process is doing anything
  3. parent process just listens to keyboard input

my $pid = fork(); if(not defined $pid){ print "error: resources not available.\n"; die "$!"; }elsif($pid == 0){ # child for(0..9){ print "doing something\n"; sleep 1; } exit 0; }else{ # parent ReadMode('cbreak'); # wait until child has exited/died while(waitpid($pid, POSIX::WNOHANG) == 0){ my $seq = ReadKey(-1); if(defined $seq){ print "got key '$seq'\n"; } sleep 1; # if ommitted, the cpu-load will reach up to 100% } ReadMode('restore'); }</lang>

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

Perl 6

Works with: Rakudo version 2018.10

<lang perl6>use Term::ReadKey;

react {

   whenever key-pressed(:!echo) {
       given .fc {
           when 'q' { done }
           default { .uniname.say }
       }
   }

}</lang>

Phix

<lang Phix>integer key = get_key() -- if key was not pressed get_key() returns -1</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 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) {

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

}</lang>

Python

<lang python>#!/usr/bin/env python

  1. -*- coding: utf-8 -*-

from __future__ import absolute_import, division, unicode_literals, print_function

import tty, termios import sys if sys.version_info.major < 3:

   import thread as _thread

else:

   import _thread

import time


try:

   from msvcrt import getch  # try to import Windows version

except ImportError:

   def getch():   # define non-Windows version
       fd = sys.stdin.fileno()
       old_settings = termios.tcgetattr(fd)
       try:
           tty.setraw(sys.stdin.fileno())
           ch = sys.stdin.read(1)
       finally:
           termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
       return ch

def keypress():

   global char
   char = getch()

def main():

   global char
   char = None
   _thread.start_new_thread(keypress, ())
   while True:
       if char is not None:
           try:
               print("Key pressed is " + char.decode('utf-8'))
           except UnicodeDecodeError:
               print("character can not be decoded, sorry!")
               char = None
           _thread.start_new_thread(keypress, ())
           if char == 'q' or char == '\x1b':  # x1b is ESC
               exit()
           char = None
       print("Program is running")
       time.sleep(1)

if __name__ == "__main__":

   main()

</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>

Racket

Using stty to get the terminal into raw mode.

<lang racket>

  1. lang racket

(define-syntax-rule (with-raw body ...)

 (let ([saved #f])
   (define (stty x) (system (~a "stty " x)) (void))
   (dynamic-wind (λ() (set! saved (with-output-to-string (λ() (stty "-g"))))
                      (stty "raw -echo opost"))
                 (λ() body ...)
                 (λ() (stty saved)))))

(with-raw

 (printf "Press a key, or not\n")
 (sleep 2)
 (if (char-ready?)
   (printf "You pressed ~a\n" (read-char))
   (printf "You didn't press a key\n")))

</lang>

REXX

The REXX language doesn't have any keyboard tools, but some REXX interpreters have added the functionality via different methods.

This version   only   works with:

  • PC/REXX
  • Personal REXX

<lang rexx>/*REXX program demonstrates if any key has been presssed. */

 ∙
 ∙
 ∙

somechar=inkey('nowait')

 ∙
 ∙
 ∙</lang>

Ring

<lang ring> if getchar() see "A key was pressed" + nl else see "No key was pressed" + nl ok </lang>

Ruby

<lang ruby> begin

 check = STDIN.read_nonblock(1)

rescue IO::WaitReadable

 check = false

end

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


Scala

<lang Scala>import java.awt.event.{KeyAdapter, KeyEvent}

import javax.swing.{JFrame, SwingUtilities}

class KeypressCheck() extends JFrame {

 addKeyListener(new KeyAdapter() {
   override def keyPressed(e: KeyEvent): Unit = {
     val keyCode = e.getKeyCode
     if (keyCode == KeyEvent.VK_ENTER) {
       dispose()
       System.exit(0)
     }
     else
       println(keyCode)
   }
 })

}

object KeypressCheck extends App {

 println("Press any key to see its code or 'enter' to quit\n")
 SwingUtilities.invokeLater(() => {
   def foo() = {
     val f = new KeypressCheck
     f.setFocusable(true)
     f.setVisible(true)
     f.setSize(200, 200)
     f.setEnabled(true)
   }
   foo()
 })

}</lang>

Seed7

The library keybd.s7i defines the file KEYBOARD and the function keypressed, which can be used to determine if a key has been pressed. <lang seed7>if keypressed(KEYBOARD) then

 writeln("A key was pressed");

else

 writeln("No key was pressed");

end if;</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.

TI-83 BASIC

TI-83 BASIC has a built in getKey function. <lang ti83b>

getKey→G

</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.

XPL0

<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations int K, N; [N:= 0; repeat K:= KeyHit; \counts up until a key is pressed

       IntOut(0, N);  ChOut(0, ^ );
       N:= N+1;

until K; ]</lang>