Main Content

Define an Object Deletion Callback

You can create an object deletion callback that executes code when you delete the object.

For example, create an object deletion callback for a figure so that when you delete the figure a dialog box appears asking if you want to delete all the figures. Copy the following code to a new function file and save it as figDelete.m either in the current folder or in a folder on the MATLAB® search path.

function figDelete(~,~)
yn = questdlg('Delete all figures?',...
    'Figure Menu',...
    'Yes','No','No');
switch yn
    case 'Yes'    
        allfigs = findobj(get(groot,'Children'),'Type','figure' );      
        set(allfigs,'DeleteFcn',[]);
        delete(allfigs)
    case 'No'
        return
end
end

Then create two figures and assign the figDelete function to the DeleteFcn properties. Delete one of the figures and choose an option on the dialog box that appears.

figure('DeleteFcn',@figDelete)
figure('DeleteFcn',@figDelete)