MATLAB: How to close a waitbar under R2014b

r2014bwaitbar

I have created a waitbar as follows:
h = waitbar(0,'1','Name','Approximating pi...',...
'CreateCancelBtn',...
'setappdata(gcbf,''canceling'',1)');
To kill this waitbar, we have to use delete(h) instead of close(h).
The problem is that during the development and testings, it is possible that the h variable is cleared or overwritten. Then the waitbar is still present but the handle is lost. In that case, how can I close the waitbar? Of course, clicking the closing X button does not work.
Thanks for your support.

Best Answer

From documentation:
You should call delete to remove a wait bar when you give it a CloseRequestFcn, as in the preceding code; calling close does not close it, and makes its Cancel and Close Window buttons unresponsive. This happens because the figure's CloseRequestFcn recursively calls itself. In such a situation you must forcibly remove the wait bar, for example like this:
set(0,'ShowHiddenHandles','on')
delete(get(0,'Children'))
However, as issuing these commands will delete all open figures—not just the wait bar—it is best never to use close in a CloseRequestFcn to close a window.