CH = getkey waits for a single keypress and returns the ASCII code. It
accepts all ascii characters, including backspace (8), space (32),
enter (13), etc, that can be typed on the keyboard.
Non-ascii keys (ctrl, alt, ..) return a NaN. CH is a double.
CH = getkey(N) waits for N keypresses and returns their ASCII codes.
getkey(1) is the same as getkey without arguments.
getkey('non-ascii') or getkey(N, 'non-ascii') uses non-documented
matlab features to return a string describing the key pressed.
In this way, keys like ctrl, alt, tab etc. can also distinguished.
The return is a string (when N = 1) or a cell array of strings.
[CH, T] = getkey(...) also returns the time between the start of the
function and each keypress. This is, however, not very accurate.
This function is kind of a workaround for "getch" in C. It uses a modal,
but non-visible window, which does show up in the taskbar.
C-language keywords: KBHIT, KEYPRESS, getkey, GETCH
Example 1 - get a single ascii key
fprintf('\nPress any key: ') ;
ch = getkey ;
Example 2 - wait for a specific key
fprintf('\nPress the Ctrl-key within 3 presses: ') ;
ch = getkey(3,'non-ascii')
if ismember('control', ch), fprintf('OK\n') ;
else fprintf(' ... wrong keys ...\n') ; end
Example 3 - Typing game
S = 'abcdefghjiklm' ;
fprintf('Type "%s" as fast as possible ...\n', S) ;
[C, T] = getkey(numel(S)) ;
C = char(C) ; T = T(end)-T(1) ;
if ~isequal(S, C), fprintf('OOPS!!! ') ; end
fprintf('You typed "%s" in %.2f seconds.\n', C, T) ;
See also input, uiwait
getkeywait (file Exchange)
Author's note: after 14 years still going strong ;-)
Jos (10584) (2019). getkey (https://www.mathworks.com/matlabcentral/fileexchange/7465-getkey), MATLAB Central File Exchange. Retrieved .
@LJM Unfortunately you cannot hide the window. See als my answer at https://uk.mathworks.com/matlabcentral/answers/374079-how-do-i-set-the-getkey-figure-as-invisible
I'm having difficulty stopping getkey drawing a figure. I have tried putting set(0,'DefaultFigureVisible','off'); and adding 'visible', 'off', to the figure code, but these don't work.
How can I use this function without a figure window?
thanks for a wonderful fucntion.. well I am new in matlab and dont know how to use your function to help me out.. i need code to input "name" and then press enter without touch keyboard.. could you please help .. thanks
Thanks, nice walk around. Though, for keyboard controller implementation it is better to use KbCheck from Psychtoolbox, as mentioned below.
I suggest you create a folder on your hard drive called "FEXfiles" or something. Add that folder to your matlab path (see the documentation how to do that). Now put your downloaded files from the File Exchange in that folder and you should be able to run it.
Sorry, I'm new here, when I download the file, in which folder I put it in?
Allows me to do batch jobs with key strokes, and also finish the job using the esc key! Simply awesome!
Great program. Is there a way to merge this program with the timer element previously implemented in the getkeywait program so that you can use a time limit for each of the multiple key presses?
Good job! :) However since I am running several parallel function, I really hope to hide the command window while keeping the figure at top...Any suggestions for me? I am trying to use matlabpool, let me see whether that would work or not...
Alrighty, I get how it works now. Not my imagined, but I can work it around. Thanks!
awesome code! Jos.
Can you explain in what sense "ability to get multiple keypresses" does?
I thought it would be like when I "release" my fingers, getkey outputs control+shift
My current impression is that getkey output "control" when I hit "control".
not having a chance to hit "shift" yet
You can modify the function. Make a for-loop to get two characters. If you need more help, please email me.
In my application, user should write two different characters consecutively and very quickly. If the user types the characters slower, there is no problem. However, when two different characters are written by the user quickly after each other, the code cannot capture them. Instead, it reads only one of the characters again and again. Do you have any suggestion for that? Thanks
Can any one please provide me with a code of keydown function and keypress function.
actually what i want to do is that when a specific key e.g. up arrow key is pressed, the ball starts moving in a circle and keeps on oving uptil the key is pressed.
as soon as that key is unpressed, the ball stops moving in a circle.
thanks in advance :)
In the above post, by 'stops moving', i intended to mean 'stops moving in a circle', and instead move in the tangential direction to the circular path. Hope it clarifies my problem.
@Andrew B: Thanks! I've implemented most of your suggestions. A new version should be up soon.
The "position" problem (if any) is, however, not easy to solve, as it seems to depend on OS, display setup, ML version ...
I made a few tweaks which you may be interested in implementing.
I added the following properties to the figure:
'position',[0 -40 1 1]
'Name','Press a key'
On Windows this places the figure off of the screen, instead of behind the taskbar. This will help ensure that the figure is not visible since some users may place their taskbar elsewhere on the screen.
It is also possible for the user to maximize the figure and then close it, which would cause an error when attempting to delete the figure handle. To procect against this use the following code:
Thanks Jos. Do you know how I can detect keypresses of the left/right arrow keys? I know it must involve use of WindowKeyPressFcn but I have no idea how to use that in syntax, since there's no example for it in the Matlab help!
@Catalin, a graphics window and a GUI window are basically the same thing, a matlab figure. Both have properties that allow to execute a piece of code (callbacks) when a key is pressed and the figure has focus.
GETKEY is primarily designed to be used when executing code in the command window.
I have the same problem as Priyanshu, namely I need to be able to read key presses but without losing focus of the current window (which is not GUI but simply a graph!). I am not sure what your suggested solution was, Jos, could you elaborate please?
@ Priyanshu, This was not designed to work in a graphical user interface. Use keypress callbacks of the gui window instead.
This function does not work well with a GUI. Once this is invoked repeatedly in a loop in GUI function the focus from the current GUI figure is lost. Is there anything that can be done in such a case?
Nice, but I have it inside a loop where I assign the ith value of a vector using getkey(). If I hit the CTRL key (to CTRL-C and break out of the loop), it stops pausing to accept input each time through the loop.
I should also add that this function doesn't wait for input. So if no keys are pressed when it is called, it is bypassed, which is great for use in a while loop.
Hey guys, I know Tristan and told him about this solution, and decided I'd post here in case any one else had this problem. I downloaded the Psychtoolbox (http://psychtoolbox.org/wikka.php?wakka=HomePage) which is free, and it has a command called KbCheck(). It can read keyboard input at any time even during a endless while loop. I drive a mobile robot using the WASD keys using it. Note: KbCheck outputs a weird key code, use KbName to convert to ASCII.
@Tristan: perhaps GETKEY is not the best option here. You could create your own key press window and use that in your code. Here is an example:
figh = figure('name','press some keys') ;
t0 = clock ;
fprintf('\nKeys pressed in 5 seconds:\n') ;
while etime(clock,t0) < 5,
curkey = get(figh,'userdata') ;
I am driving a virtual robotic arm with getkey. It works but it crashes if I hold a key down. Does anyone know of a way to allow for continuous input?
Good job. Worked for me
To Jens Rantil: GETKEY is not at all as trivial as your code implies. For instance, GINPUT needs an axis (and will create one if none exist) and can capture only a few keys.
GETKEY has none of this behavior, and is much more flexible as it can be used in codes without graphical output.
This program is unnecvessary as it can be done using
Did the job perfectly for me.
to Fred Kluger: you may use this wherever you want a single key response from the user. You can use it in similar way as you would use <input> (which requires an additional "enter")
to Erik: ??
How can I use this?
Great! been searching for something like this for ages..
Just what I was looking for.
Chris, could you elaborate please? Running
'for i = 1:100, a = input('Enter a letter','s'), end', I didn't see any irregularities. (How many is so many?)
Jos, maybe you could write a companion function that outputs the key pressed now, rather than waits for one, as INPUT? I don't really know of any way - including via 'currentkey' figure property - to do that in Matlab, and a solution would be very helpful.
The INPUT function in R13 contains a bug that does not flush the keyboard buffer while within loops, meaning that after so many calls the keyboard will stop working.
As a result, getkey is especially useful to me. Thank you for making it available.
modernised & added typing game example
Update 2.0 (june 2012): ability to get multiple keypresses
changed some figure properties; added check of figure existence
tested for newer releases
added some minor improvements
Create scripts with code, output, and formatted text in a single executable document.