How to make MATLAB detect keyboard stroke?

637 views (last 30 days)
M Min
M Min on 16 Apr 2017
Commented: Caden Scharpf on 21 Apr 2020
I want to write a code which detect left and right arrow stroke in keyboard.
I tried to use below kind of code but it shows crosshair and also interrupts the working of other line. (Making crosshair invisible is somewhat important in this case)
switch button
case 28 %left
case 29 %right
Is there any better way to do it? Thanks!

Accepted Answer

Nirav Sharda
Nirav Sharda on 18 Apr 2017
There are a couple of ways to achieve this. You can use the KeyPressFcn callback on the figure window. Here is an example.
h_fig = figure;
The myfun here could have something like this.
function myfun(src,event)
The other way to achieve this is to use ' waitforbuttonpress ' function. Here is an example code.
k = waitforbuttonpress;
% 28 leftarrow
% 29 rightarrow
% 30 uparrow
% 31 downarrow
value = double(get(gcf,'CurrentCharacter'))
I hope this helps.

Sign in to comment.

More Answers (1)

balandong on 23 Mar 2020
Maybe Im bit late to join the party. But you can consider this FEX submission KbTimer. It is MEX base thus quite fast

Community Treasure Hunt

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

Start Hunting!