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

Version 1.0.0.0 (4.51 KB) by Amanda
Returns last key pressed in command window without having to explicitly wait for input. M-file & MEX
2.1K Downloads
Updated 3 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.

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

kbhit('init');
fprintf(1, 'Five seconds to type something ...');
pause(5);
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);
kbhit('stop')

Example use of MEX library :

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

Cite As

Amanda (2024). Non-wait detection of keyboard input (including MEX implementation) (https://www.mathworks.com/matlabcentral/fileexchange/30622-non-wait-detection-of-keyboard-input-including-mex-implementation), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2008b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Argument Definitions in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!

mexKbhit/

Version Published Release Notes
1.0.0.0