1

我有一个简单的 GUI 代码,如下所示。这个“test_keypress”函数创建一个图形,它响应按键(空格)。

现在,我想添加一个约束,以便 Matlab 在一段时间内(比如 1 秒)只接受一个按键。换句话说,如果在上一次按键发生后 1 秒内发生按键,我想拒绝它。

我怎样才能做到这一点?

function test_keypress

f = figure;
set(f,'KeyPressFcn',@figInput);
imshow(ones(200,200,3));

end


function figInput(src,evnt)

if strcmp(evnt.Key,'space')
    imshow(rand(200,200,3));
end

end
4

1 回答 1

3

You can store the current time, and only evaluate the imshow command if the key-press occurs at least 100 seconds after the last one.

function test_keypress

f = figure;
set(f,'KeyPressFcn',@figInput);
imshow(ones(200,200,3));

%# initialize time to "now"
set(f,'userData',clock);

end


function figInput(src,evnt)

currentTime = clock;
%# get last time
lastTime = get(src,'UserData');

%# show new figure if the right key has been pressed and at least
%# 100 seconds have elapsed
if strcmp(evnt.Key,'space') && etime(lastTime,currentTime) > 100
    imshow(rand(200,200,3));
    %# also update time
    set(src,'UserData',currentTime)
end

end
于 2012-12-10T16:42:23.273 回答