Code covered by the BSD License  

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

Be the first to rate this file! 16 Downloads (last 30 days) File Size: 4.51 KB File ID: #30622

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

by Amanda

 

03 Mar 2011

Returns last key pressed in command window without having to explicitly wait for input. M-file & MEX

| Watch this File

File Information
Description

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

MATLAB release MATLAB 7.7 (R2008b)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Tag Activity for this File
Tag Applied By Date/Time
kbhit Amanda 03 Mar 2011 15:38:50
mex Amanda 03 Mar 2011 15:38:51
getkey Amanda 03 Mar 2011 15:38:51
interrupt Amanda 03 Mar 2011 15:38:51
poll Amanda 03 Mar 2011 15:38:51
getchar Amanda 03 Mar 2011 15:38:51
kbhit Panorama 08 Nov 2011 08:48:34

Contact us at files@mathworks.com