File Exchange

image thumbnail


version 2.1 (2.8 KB) by Jos (10584)
Get a keypress


Updated 11 Feb 2019

View Version History

View License

Editor's Note: This file was selected as MATLAB Central Pick of the Week

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 ;
fprintf('%c\n',ch) ;

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

Cite As

Jos (10584) (2021). getkey (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (45)

Muhamed Ali

this is what i have been looking for... thanks


Nice submission. I was looking through the 2019 year in review and I noticed this post.

I have a suggestion for the figure being functionally invisible. If I set the Units property of the figure to Pixels and use the following code as the Position I don't see it: mon=max(get(0,'MonitorPositions'),1);pos=[mon(3:4) 1 1];%use max in case of multiple monitors

Looking through the function I also noticed one tiny thing: despite the comment text, this function is not compatible with v6.5. It uses toc with an input, which was undocumented since v7.1 (possibly v7.0) and documented since R2008b. If you want to keep the compatibility, you will have to use the now function. (also narginchk didn't exist)

Chang hsiung

Jos (10584)

@LJM Unfortunately you cannot hide the window. See als my answer at


Hi Jos,

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?




Muhammad RSMY

hi Jos

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.

Javier Valdes


Jos (10584)

@ Oscar,

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.

Oscar Alejandro

Sorry, I'm new here, when I download the file, in which folder I put it in?

Lars Henrik Bolstad

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?

Yulan Liu

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

Chaowei Chen

Alrighty, I get how it works now. Not my imagined, but I can work it around. Thanks!

Chaowei Chen

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

Jos (10584)

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


Hey everone!!
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.

Jos (10584)

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

Andrew Bytheway

Great work.

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:

if ishandle(fh)
delete(fh) ;

AwedBy Matlab

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!

Jos (10584)

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

AwedBy Matlab

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?

Jos (10584)

@ Priyanshu, This was not designed to work in a graphical user interface. Use keypress callbacks of the gui window instead.

Priyanshu Agarwal

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?

Jeff Vipperman

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

Jos (10584)

@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') ;
set(figh,'windowkeypressfcn','set(gcbf,''Userdata'',get(gcbf,''CurrentCharacter''))') ;
set(figh,'windowkeyreleasefcn','set(gcbf,''Userdata'','''')') ;
t0 = clock ;
fprintf('\nKeys pressed in 5 seconds:\n') ;
pause ;
while etime(clock,t0) < 5,
curkey = get(figh,'userdata') ;
if ~isempty(h),
fprintf('%c',curkey) ;
pause(.05) ;
fprintf('\n') ;
delete(figh) ;


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?

gregor samsa

Good job. Worked for me

Jos (the author)

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.

Jens Rantil

This program is unnecvessary as it can be done using

Jay Vaughan

Did the job perfectly for me.

Jos van der Geest

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


fred klugger

How can I use this?

Erik Helberg

Patrick Craston

Great! been searching for something like this for ages..

George Aumann

Just what I was looking for.

Dimitri Shvorob

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

Chris Brown

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.

MATLAB Release Compatibility
Created with R2018b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!