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...');
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)
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.
Best Answer