首页 > 解决方案 > WindowKeyPressFcn 程序中断后执行

问题描述

在 while 循环中运行 matlab 脚本时,我想检测按键的按下。目前,我只想success在按下键后显示 。不幸的是,该消息仅在程序中断 ( CTRL+ C) 后显示,而不是在程序运行期间显示。这是代码:

% 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

标签: matlabcallback

解决方案


您需要打破正在运行的脚本的循环,以便 Matlab 处理其他事件,本质上是您的按键。你可以通过在你的while循环中添加一个drawow来做到这一点,下面的代码应该足以让你合并到你自己的代码中:

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

推荐阅读