Latest version with better compatibility with the original functions. For those interested this restores the figure focus policy that matlab used prior to 2006 and works nicely with focus follows mouse arrangements. It gives priority over figure focus to the CLI and scripts over where the mouse has been / been clicked.
The documentation for figure() and axes() is rather woolly on my version so I've attempted to reproduce the observed behaviour rather than anything else.
figure.m
%%fix the annoying focus follows mouse bug
%%(c) GPL SA 2013 v1.0
function h=figure(varargin);
global hasfocus;
if(nargin<2)
if(nargin<1)
n=1;
else
n=varargin{:};
end
h=builtin('figure',n);
jFig = get(h,'JavaFrame');
jAxis = jFig.getAxisComponent;
set(jAxis,'FocusGainedCallback',{@setfocus,h});
hasfocus=h;
else
h=builtin('figure',varargin{:});
end;
axes.m
%%fix the annoying focus follows mouse bug
%%(c) GPL SA 2013 v1.0
function h=axes(varargin);
global hasfocus;
if(nargin~=1)
%%in this circumstance we'll either create an axes in the current figure
%%or create a new axes both of which are handled here and we return the axes
%%handle
h=builtin('axes',varargin{:});
hasfocus=get(h,'Parent');
return;
end
if(nargin==1)
%%under this circumstance axes does not return a handle
%%if it is successful we should make this figure current
%%since this axes will be current, but if not we'll throw
%%an error and keep the same focus
if(nargout>0)
%%try to maintain compatibility with builtin('axes')
%%by throwing this error if a return is asked for here
error('MATLAB:maxlhs','Too many output arguments.')
end;
try
builtin('axes',varargin{1});
%%since there was no error we set the focus appropriately
hasfocus=get(varargin{1},'Parent');
catch
%%we caught the error
rethrow(lasterror)
disp('some error in case it wasn''t printed');
end
return;
end;
if true
% code
end
setfocus.m
%%fix the annoying focus follows mouse bug
%%(c) GPL SA 2013 v1.0
function setfocus(jAxis, jEventData, hFig)
global hasfocus;
%%deal with the case when the focussed window has been lost
%%I can't remember what the correct behaviour should be so
%%I'll resort to doing nothing / focusing the current window
%%and setting the focus to the current window - nasty
t=get(0,'Children');
t=find(t==hasfocus);
if(isempty(t))
%printf('Trying to focus a dead window doing nothing',hFig);
hasfocus=hFig;
return
end;
set(0,'currentfigure',hasfocus)
end