One can typically call the CloseRequestFcn of a GUI to cleanly exit from it. However, calling it directly from the OpeningFcn is not desirable for a clean exit because the GUI is not fully initialized at that point. After exiting from the OpeningFcn the OutputFcn of a GUI is called by the GUIDE execution infrastructure. At the end of this function, the initialization of a GUI is complete and it is safe to call the CloseRequestFcn.
As an example, consider the following implementation of the OpeningFcn and the OutputFcn. This example uses CloseRequestFcn to close the GUI. To generate a default CloseRequestFcn, open the GUI in GUIDE, right-click on the figure and select ViewCallbacks -> CloseRequestFcn. This will open the MATLAB file for the GUI. Modify CloseRequestFcn if needed, then save the MATLAB GUI file.
function myGUI_OpeningFcn(hObject, eventdata, handles, varargin)
handles.output = hObject;
if ~isempty(varargin) && ischar(varargin{1}) && strcmp(varargin{1},'exit')
handles.closeFigure = true;
end
guidata(hObject, handles);
function varargout = myGUI_OutputFcn(hObject, eventdata, handles)
varargout{1} = handles.output;
if (isfield(handles,'closeFigure') && handles.closeFigure)
figure1_CloseRequestFcn(hObject, eventdata, handles)
end
function figure1_CloseRequestFcn(hObject, eventdata, handles)
delete(hObject);
The above solution relies on the OutputFcn being called right after the OpeningFcn when adequate inputs are not provided and the GUI must exit. If one wishes to stop the execution of OutputFcn by using UIWAIT, for cases where adequate inputs are provided, a conditional UIWAIT can be placed in the OpeningFcn. The corresponding UIRESUME can be placed in any of other functions as desired.
Best Answer