Howto : Prevent figures from stealing focus in MATLAB

Regular users of MATLAB will have noticed that figure windows have a nasty tendency to steal the focus from other windows. If you are making regular updates to a figure while in a loop, this makes it impossible to, say, use a browser while the script is running. Read on for a solution to this problem(!)

To get around this, download this script: sfigure.m and put it in your MATLAB path (or in your current working directory). Then replace all calls to figure() with calls to sfigure(). Now, your figures will no longer take focus.

The code can be seen below.

function h = sfigure(h)
% SFIGURE  Create figure window (minus annoying focus-theft).
%
% Usage is identical to figure.
%
% Daniel Eaton, 2005
%% See also "help figure"
if nargin>=1
if ishandle(h)
    set(0, 'CurrentFigure', h);
else
    h = figure(h);
end
else
    h = figure;
end

Credits:
Daniel Eaton. http://www.cs.ubc.ca/~deaton/

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google

7 thoughts on “Howto : Prevent figures from stealing focus in MATLAB

  1. You copied the code wrong and left out the first line. It should be:

    if nargin>=1
    if ishandle(h)
    set(0, ‘CurrentFigure’, h);
    else
    h = figure(h);
    end
    else
    h = figure;
    end

  2. Many, many, many thanks for this! It’s great to be able to do something else while MATLAB plots away. Works like a charm.

  3. Hi, this code does not work for me, Matlab says:
    ??? Error using ==> sfigure
    Too many input arguments.

    So I modify the code with the following which works well:

    function h = sfigure(varargin)
    if nargin>=1
    if ishandle(varargin{1})
    set(0, ‘CurrentFigure’, varargin{1});
    else
    h = figure(varargin{:});
    end
    else
    h = figure;
    end

    Thanks anyway!

  4. Thanks, this trick works like a charm.
    I went one step further. In order to get full functionality of figure with a variable input number of arguments (properties) and overloading the builtin figure you can use:

    function varargout = figure(varargin)
    if nargin>=1
    if ishandle(varargin{1})
    set(0, ‘CurrentFigure’, varargin{1});
    else
    h = builtin(‘figure’,varargin{:});
    end
    else
    h = builtin(‘figure’);
    end
    if nargout
    varargout(1) = {h};
    end

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>