programmatically setting "Confirm before exit MATLAB"

26 views (last 30 days)
Weiliang Dai
Weiliang Dai on 11 Feb 2026 at 20:55
Commented: dpb on 12 Feb 2026 at 20:31
I like to set the preference "Confirm before exit MATLAB" that can be set through preferences->general->confirmation dialog->confirm before exit matlab through script. I have following code for test,
function TestExit(action)
if ~nargin
action = 'init';
end
switch action
case 'init'
% Initialize the GUI
h0 = figure('Visible','off','WindowStyle','normal');
% Add close event callback
%set(h0, 'CloseRequestFcn', ...
% 'TestExit(''close'');');
% Enable "Confirm before exit MATLAB"
setpref('MATLAB', 'ConfirmExit', true);
% Check the current value
getpref('MATLAB', 'ConfirmExit')
case 'close'
ans = questdlg('Are you sure you want to quit?', ...
'Exit', 'Yes', 'No', 'Yes');
if strcmp(ans, 'No')
return;
end
% Close and exit the program
delete(gcf);
quit
end % End switch
end
I tested with multiple versions of MATLAB (R2020a through R2025b), it all failed to popup the confirmation dialog and exit MATLAB. I can manually start matlab, turn on the preference through GUI, and it works. my question is, is there a way to do it using scripts.
Thanks,
weiliang
  4 Comments
Weiliang Dai
Weiliang Dai about 2 hours ago
Thx. I tested using finish.m and it does intercept the click 'X' on matlab window and popup dialog. and I can choose to accept quit or cancel to continue. My use case is, I have a Qt based engine app. I set the visibility for the matlab main window through the engine. If user click on 'X' on the main window, and the finish.m is in the path, it will prompt user for confirmation. The only additional thing I need to do is to make sure to remove the path to finish.m before I call engClose.
dpb
dpb about 1 hour ago
Is this Qt starting/controlling a MATLAB app, I gather? If that's the case, then you can add a callback function in in on the 'UIFigureCloseRequest' that traps the user action to close the window by whatever means. The default appdesigner code template for the callback function is
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app)
end
Insert the user dialog call therein before the delete(app) statement with any other cleanup wanted/needed and you won't have to mess around with the user preferences nor mucking with the install path.

Sign in to comment.

Answers (0)

Categories

Find more on Interactive Control and Callbacks in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!