I have a GUI and I want to repeat some process from the time the given key is pressed until the key is released.
I know how to do some process once when the key is pressed. But is there any way how to for example display random number every second until the key is released?
Thank you for your answers. Jaja
You can attach a timer to your figure, start it with the KeyPressFcn
and stop it with the KeyReleaseFcn
.
The example below will create a figure, and display a random number in the console as long as the key f is pressed.
function h=keypressdemo
h.fig = figure ;
%// set up the timer
h.t = timer ;
h.t.Period = 1 ;
h.t.ExecutionMode = 'fixedRate' ;
h.t.TimerFcn = @timer_calback ;
%// set up the Key functions
set( h.fig , 'keyPressFcn' , @keyPressFcn_calback ) ;
set( h.fig , 'keyReleaseFcn' , @keyReleaseFcn_calback ) ;
guidata( h.fig ,h)
function timer_calback(~,~)
disp( rand(1) )
function keyPressFcn_calback(hobj,evt)
if strcmp(evt.Key,'f')
h = guidata(hobj) ;
%// necessary to check if the timer is already running
%// otherwise the automatic key repetition tries to start
%// the timer multiple time, which produces an error
if strcmp(h.t.Running,'off')
start(h.t)
end
end
function keyReleaseFcn_calback(hobj,evt)
if strcmp(evt.Key,'f')
h = guidata(hobj) ;
stop(h.t)
end
This is a simple timer mode and the callback function take a lot less time than the interval so no problem to expect here. If you want whatever function to re-execute itself right after it's finished (kind of infinite loop), you can set that up by changing the executionmode
of the timer (read the timer
documentation for examples.
However, be aware that if your callback execute permanently and consume all the (matlab unique) thread ressource, your GUI might become less responsive.