0

This is a MATLAB GUI. And I have a while loop running. But while in the loop i need to use keyboard inputs which are a different callback. Is there a way or is it possible to execute that callback while it is in the loop?

Note: I am using GUIDE

3
  • Do you mean that inside the while loop you want keyboard inputs to call various functions inside the while loop? Commented Jul 27, 2013 at 19:36
  • These are callback functions for a GUI generated by GUIDE Commented Jul 27, 2013 at 20:49
  • Ahhhhh that is quite different from what I thought. Thanks for clarification. Commented Jul 28, 2013 at 1:50

1 Answer 1

1

Yes, this is possible. You just need to get the character data from the keypress callback to the callback that is in a loop. One way of doing this is via the figure guidata.

For example, if your loop is running from a button callback and you want to see a keypress on the figure you could use the following:

Button Callback

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)

fig = get(hObject,'Parent');
for i=1:1000
    pause(0.01);
    % Get the latest guidata
    handles = guidata(fig);
    if isfield(handles,'KeyData' ) && ~isempty(handles.KeyData)
        fprintf(1,'Pressed : %s\n', handles.KeyData.Character);
        % Clear the keydata we have now handled.
        handles.KeyData = [];
        guidata(fig,handles);
    end
end    

Figure keypress callback

% --- Executes on key press with focus on figure1 and none of its controls.
function figure1_KeyPressFcn(hObject, eventdata, handles)

% Store the keypress event data for use in the looping callback
handles.KeyData = eventdata;
guidata(hObject,handles);
Sign up to request clarification or add additional context in comments.

6 Comments

Does the for loop go in the while loop I have?
@Chandough - Yes, I just wrote it as a for loop to show how it could work. You just need the code from % Get the latest guidata down.
Which part didn't work? figure1_KeyPressFcn not called and so handles.KeyData not set or code in loop doesn't work.
Really difficult to help with so little information. Are there any details you have found that you think may be relevant? For example, the handles structure is always empty, the handles structure doesn't have a KeyData field, the KeyData field is there but always empty. I'm presuming you know how to set breakpoints in Matlab code and know how to examine variables.
The handles data structure stores something but, when its printing 'pressed:' its just blank. It prints one time and doesn't display anything apart from 'pressed:'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.