File Exchange

image thumbnail

Non-wait detection of keyboard input (including MEX implementation)

version (4.51 KB) by Amanda
Returns last key pressed in command window without having to explicitly wait for input. M-file & MEX


Updated 03 Mar 2011

View License

These functions retrieve the last key pressed in the command window without having to explicitly wait for input. Useful for situations where code is executing and you want to poll for keyboard input but you don't want hidden figures. For example, mexKbhit can be used to interrupt a MEX function while it's executing.

The code taps into the command window's key press callback function. Each time a key is pressed, a small piece of m code is run to save the key event. A call to kbhit (or mexKbhit in MEX code) will return information about the key event, such as the ascii code and the related character, and whether Control, Alt and/or Shift was also entered.

Warning : mexKbhit calls the matlab function kbhit. While CTRL+C doesn't interrupt MEX functions, it will interrupt matlab functions called by a MEX function. Therefore, the key combo CTRL+C may cause problems when your MEX function is executing mexKbhit.

Big acknowledgements to Yair Altman in the MATLAB newsreader thread "java: add keyListener to command window", for providing the exact code needed to set up the key press callback.

kbhit.m - matlab function
mexKbhit.h - MEX c file header
mexKBhit.c - MEX c file, including instructions for building the library
mexKbhitDemo.c - demonstration code for using the MEX library.

Example use of Matlab function :

fprintf(1, 'Five seconds to type something ...');
key = kbhit; fprintf(1, 'Character : %c\n', key);
key = kbhit('struct'); fprintf(1, 'Key struct :\n'); disp(key)
[key, ctrlc] = kbhit('event'); fprintf(1, 'Key event :\n'); disp(key)
fprintf(1, 'Ctrl+c pressed ? %d\n', ctrlc);

Example use of MEX library :

clock_t t;
struct key k;
t = clock();
// poll for 5 seconds
mexPrintf("Wait 5 seconds ... ");
while ((clock()-t)/CLOCKS_PER_SEC < 5) {
k = mexKbhit();
if (k.character == 'C' && k.ctrl == 1) {
mexPrintf("interrupted by Ctrl+c! ");

Comments and Ratings (5)

Same issue here... ver. 2016b. A possibility to set uiwait to a minimum of zero (instead of 1s) for dialog functions would be quite helpful!

Neil Weiss

Same issue here

Misaki Soma

I have the same error than Yuval Aviel, someone knows how to solve this issue? (On matlab 2017)

Yuval Aviel

unfortunately, there is an issue with kbhit.m on version 2014a;

after kbhit('init'), I get the following error message for every keystroke on the command window:

The name 'Userdata' is not an accessible property for an instance of class

the error message stops after kbhit('stop');

can you please fix it??


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