Keyboard input/Keypress check: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added BBC BASIC)
m (wiki grouping)
Line 1: Line 1:
{{task}}
{{task|Keyboard input}}


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

Revision as of 19:21, 24 January 2013

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.

BASIC

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>

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>

Euphoria

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

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>

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

import thread import time


try:

   from msvcrt import getch

except ImportError:

   def getch():
       import sys, tty, termios
       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

char = None

def keypress():

   global char
   char = getch()

thread.start_new_thread(keypress, ())

while True:

   if char is not None:
       print "Key pressed is " + char
       break
   print "Program is running"
   time.sleep(5)</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>

REXX

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

Works with: PC/REXX

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

 ∙
 ∙
 ∙

somechar=inkey('nowait')

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