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/




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
This doesn’t work for me
The code should be fixed now!
Doesn’t work for me either. I’m on Linux (KDE 4/Ubuntu)
Many, many, many thanks for this! It’s great to be able to do something else while MATLAB plots away. Works like a charm.
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!
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