Clear Filters
Clear Filters

How do I write in a function to close the screen if a certain button is pressed? PTB

10 views (last 30 days)
Hi,
I have a fairly complex experiment code I am running in matlab in conjunction with psychtoolbox. To cut a long story short the script runs a number of trials in for-loops split into 4 separate runs e.g.:
Open onscreen window ..BLAH BLAH.. for i=1:12; % scripts [onsetTimesTot(i,:), responsesTot(i,:), kpTot(i,:)] = presentStory(i, screenparms, ... expinfo, scriptID ,script, scriptCond, imcell, handle, subject); end
Basically I am trying to figure out a way of including a piece of code that will exit the script (and close the open window) if a person presses the esc key at any point during the experiment. Sounds simple but I just cannot get anything I try to work.... The suggestions online are to spam ctrl+c then type sca and press enter which is very unreliable and doesn't work half the time!
Does anybody know an easy bit of code I could add in to do this?
Thanks in advance and sorry for the rookie question!

Accepted Answer

Naman Chaturvedi
Naman Chaturvedi on 27 Jul 2018
Hi Andrew, You can make a small uicontrol object like a pushbutton and use delete(gcbf) in callback. Check the code given below.
function A
f=figure;
p=uicontrol('Parent',f,'Style','pushbutton','Callback',{@C},'Position',[50 50 100 100]);
B(f);
end
function B(f)
e=uicontrol('Parent',f,'Style','edit','String','0');
while(ishandle(f))
e.String=num2str(randn);
pause(0.3);
drawnow();
end
end
function C(~,~)
delete(gcbf);
end
Hope this helps. MATLAB does not have a function that scans for keyboard activity without interrupting the event stream.
However, if your program involves a figure window, you can utilize the ‘KeyPressFcn’ property. Refer to this link if you want to know how to do that:-
https://www.mathworks.com/matlabcentral/answers/100980-how-do-i-write-a-loop-in-matlab-that-continues-until-the-user-presses-any-key

More Answers (0)

Products


Release

R2016a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!