WindowKeyPressFcn executes after program interruption

Viewed 47

I want to detect pressing of the key, when running matlab script in while loop. At the moment, I only want to display success, after pressing of the key. Unfortunately, the message is displayed only after program interruption (CTRL+C) not during program run. Here is the code:

% Init of callback
fig = gcf;
set(fig,'WindowKeyPressFcn',@keyPressCallback);


% keyPressCallback function
function keyPressCallback(source,eventdata)
    keyPressed = eventdata.Key;
    if strcmpi(keyPressed,'space')
        disp('success');
    end
end
1 Answers

You need to break the cycle of the script which is running so that Matlab will process other events, in essense your keypress. You can do that by adding a drawnow inside you while loop, the code below should give you enough to incorporate in your own:

fig = figure;
set(fig,'WindowKeyPressFcn',@(hFig,hEvent)fprintf('pressed key %s\n',hFig.CurrentKey) );
drawnow();
while true
  if ~ishandle(fig); break; end
  drawnow();
end
Related