I would do it just like I showed you before, but add a keyreleasefcn. So when the user pushes the correct key, a value is set. Subsequent calls to the keypressfcn are ignored unless the value is unset by the keyreleasefcn. For example (recall you may want to use windowkeypressfcn and windowkeyreleasefcn instead...):
function youPressedSpaceBrah2
S.tm = 0;
S.tm(2) = 1;
S.fh = figure('KeyPressFcn',@youPressedSomething,...
'KeyReleaseFcn',@youReleasedSomething,...
'menu','none',...
'pos',[400 400 320 50]);
S.th = uicontrol('Style','text','Position',[10 10 300 30],...
'String','You have not hit space yet');
S.cnt = 0;
S.R = 1;
function youPressedSomething(varargin)
if ~S.R
return
else
S.R = 0;
end
S.tm(2) = now;
if diff(S.tm)*86400>10
S.tm(1) = now;
S.cnt = 0;
end
if strcmp(varargin{2}.Character,' ')
S.cnt = S.cnt + 1;
set(S.th,'str',sprintf('You hit space %i times brah!',S.cnt));
end
end
function youReleasedSomething(varargin)
S.R = 1;
end
end
.
.
.
Here is another example. This one does not use nested functions, so it is more like what you might find when working with at GUI built by GUIDE. Notice that I use the GUIDATA function throughout. Your code will differ, of course, but I think you can get the idea....
.
.
.
function youPressedSpaceBrah3
S.tm = 0;
S.tm(2) = 1;
S.fh = figure('KeyPressFcn',@youPressedSomething,...
'KeyReleaseFcn',@youReleasedSomething,...
'menu','none',...
'pos',[400 400 320 50]);
S.th = uicontrol('Style','text','Position',[10 10 300 30],...
'String','You have not hit space yet');
S.cnt = 0;
S.R = 1;
guidata(S.fh,S)
function youPressedSomething(varargin)
S = guidata(gcbf);
if ~S.R
return
else
S.R = 0;
end
S.tm(2) = now;
if diff(S.tm)*86400>10
S.tm(1) = now;
S.cnt = 0;
end
if strcmp(varargin{2}.Character,' ')
S.cnt = S.cnt + 1;
set(S.th,'str',sprintf('You hit space %i times brah!',S.cnt));
end
guidata(gcbf,S)
function youReleasedSomething(varargin)
S = guidata(gcbf);
S.R = 1;
guidata(gcbf,S)
Best Answer