首页 > 解决方案 > 设置用户输入的时间限制

问题描述

我正在做一个项目。其中一部分需要用户对图形做出反应。目标:必须在有限的时间内(例如 1 秒)按下一个键,否则图形将关闭。这是我到目前为止所拥有的:

test = figure;
tic;
pause;
input = get(gcf, 'CurrentCharacter');
reaction_time = toc;
close;

我一直在互联网上寻找添加时间限制的解决方案。我试过while循环,timer但我就是想不出正确的方法。我会很感激任何事情。

标签: matlab

解决方案


我认为,经过一些调整,这就是您正在寻找的。代码里面的解释:

% Let's define a control struct called S: 
global S; % We need to be able to actually change S in a function, but Matlab passes variables by value.

% Add to S all information you need: e.g. a figure handle 
S.f = figure;  % Add in the figure handle
S.h=plot(rand(10,1));  % Plot something on it  

% Define a boolean flag to capture the click: 
S.user_has_clicked = false; 

% Add a button to the figure - or anywhere else: 
S.pb = uicontrol('style','push','units','pix','position',[10 10 180 40],...
                 'fontsize',14,'string','Change line',...
                 'callback',@pb_callback);

% Define a timer object with a timeout of 3 seconds: 
timer_o = timer('StartDelay', 3, 'TimerFcn', @timer_callback); 

% Start the timer, and continue computing
start(timer_o)

% Some compute code, or simply pause(3); 
while(1)
    pause(1); 
    disp('Computing for another second'); 
end

% The push button callback: 
function pb_callback(varargin) 
global S 
S.user_has_clicked = true; 
disp('Captured a click'); 
end

% The timer callback: 
function timer_callback(timer_o,~) % 
    global S 
    if ~S.user_has_clicked
        disp('Timeout reached with no button click - Closing figure'); 
        close(S.f); 
    else
        disp('Detected user click in timeout callback');
    end
end

推荐阅读