MATLAB: Close message box if user doesn’t

msgbox

I am trying to use a message box to let a user know that the program is running (this program will be deployed as a standalone executable) and I want to make sure if they click ok on the message box, it doesn't break things. Here is what I was trying:
handle = msgbox('Please wait...');
%Do stuff
if exist('handle', 'var')
delete(handle);
clear('handle');
end
The problem is, while I'm "%doing stuff", the msgbox won't go away while clicking ok but when the stuff is done, it does and it still enters the if loop and tries to delete 'handle' which isn't open any more but is still a listed variable.
Recommendations?

Best Answer

There may be a couple of solutions to this. The first is the ishandle function which tests for a valid graphics or Java object handle. Your above code would become
handle = msgbox('Please wait...');
%Do stuff
if ishandle(handle)
delete(handle);
end
clear handle;
This seems to work. I just replaced the Do stuff with a pause(10) and there were no problems if I pressed OK, pressed the X (close button), or did nothing.
An alternative is to add a callback to the message box to capture the case where the user deletes it (i.e. presses OK or the X close button). Note that I've pasted the above code in a function called test so that I could wrap the entire function in a block
function test
handle = msgbox('Please wait...');
set(handle, 'DeleteFcn', @delete_fcn_callback)
% Do stuff
if ~isempty(handle)
delete(handle);
end
clear handle;
function delete_fcn_callback(~,~)
handle = [];
end
end
The above is more cumbersome than the first example, with its main purpose to set the handle local variable (which is accessible in the nested function) to an empty array so that the subsequent check against this variable (once all work has completed) can then either delete the handle (if it still exists) or just clear the local variable.
Note that the clearing of the local variable handle (in both examples) is not really necessary. You could just as easily "clear it" by setting it to an empty array/vector.