Search code examples
matlabfigure

Matlab waitbar - close all doesn't work


I have some code which creates a waitbar:

if long_process %user specifies this true/false
    h = waitbar(1/4, msg);
end
process(arg1,arg2);

Process is some function which does some plotting. If I do CTRL-C somewhere in process and I get left with a figure window I can just do close all and the figure disappears. However, the waitbar stays. I don't know how to make that thing close with 'close all'.

The reason this is bothering is because when I start debugging I often end up having 20+ waitbars open. 'close all' then comes in handy.


Solution

  • Actually, the close function gives you some more "forceful" options:

    close all hidden
    close all force
    

    And if for some reason those don't work, one "nuclear" option you have is to delete all figures, including those with hidden handles, as suggested in the close and waitbar documentation:

    set(0, 'ShowHiddenHandles', 'on');
    delete(get(0, 'Children'));
    

    You may find it easiest to create your own helper function to do this for you (and return the state of 'ShowHiddenHandles' to its default 'off' state) so you don't have as much to type:

    function killEmAll
      set(0, 'ShowHiddenHandles', 'on');
      delete(get(0, 'Children'));
      set(0, 'ShowHiddenHandles', 'off');
    end
    

    ...And even a third option is to try and avoid the problem altogether (if the organization of your code allows it) by using onCleanup objects! If you run the following sample code, the waitbar should be automatically deleted for you when you CTRL-C out of the infinite loop:

    function runprocess
      h = waitbar(1/4, 'la la la...');
      waitObject = onCleanup(@() delete(h));
      process();
    end
    
    function process
      i = 1;
      while (i > 0)
        i = i + 1;
      end
    end