MATLAB: How to change ‘CloseRequestFcn’ property of a figure, so when the figure is reopened, it uses a different ‘CloseRequestFcn’

MATLAB

I have a figure window associated with a GUI. I want the figure window to remain open until the user exits the GUI. I have removed the figure 'CloseRequestFcn'. However, when I save the figure, and reopen it, I am unable to close the figure because it has no 'CloseRequestFcn'.

Best Answer

Modification of the 'CloseRequestFcn' can occur upon re-openging the figure using the 'CreateFcn'. Try the following example:
plot(1:10)
set(gcf, 'CloseRequestFcn', 'disp(''closing figure...''); closereq')
set(gcf, 'CreateFcn', 'set(gcf, ''CloseRequestFcn'', ''closereq'', ''CreateFcn'', '''')')
hgsave myFigure
This example creates a figure with a simple line plot. In line 2, the ‘CloseRequestFcn’ is altered to display “closing figure…” at the Command Prompt when the figure is closed. In line 3, the ‘CreateFcn’ is set to a command which resets both the ‘CloseRequestFcn’ and the ‘CreateFcn’ to their default values.
After executing the example, examine the ‘CloseRequestFcn’ and ‘CreateFcn’ properties by entering the following at the MATLAB Command Prompt:
get(gcf, CloseRequestFcn)
get(gcf, CreateFcn)
When you close the figure, you will see “closing figure…” at the MATLAB Command Prompt.
Reopen the figure by executing:
open myFigure.fig
Then examine the ‘CloseRequestFcn’ and ‘CreateFcn’ properties. Note that both of these properties have been reset to their default values. The figure will now close properly when the user exits the figure. These new properties will be saved if you resave the figure, otherwise the ‘CloseRequestFcn’ and ‘CreateFcn’ will continue to be reset each time the figure file is loaded.