I have a simple question, although it\'s harder than it seems; I couldn\'t find the answer on the interwebs :O
I\'m writing a script in Matlab. What I want to do is
KeyPressFcn is good because it forces you to write event-driven code. Which is generally a good idea! However, if KeyPressFcn doesn't seem right for you, for example if you must keep running in a loop, and you just want to poll whether a key has been pressed, I found this solution buried in the matlab website:
get(gcf,'CurrentCharacter')
Then you could set this property to a blank, and poll it as required. e.g:
finish=false;
set(gcf,'CurrentCharacter','@'); % set to a dummy character
while ~finish
% do things in loop...
% check for keys
k=get(gcf,'CurrentCharacter');
if k~='@' % has it changed from the dummy character?
set(gcf,'CurrentCharacter','@'); % reset the character
% now process the key as required
if k=='q', finish=true; end
end
end
This worked well for me in 2014b. The downside is that the graphics window needs to be focused to receive the key events.