www.gusucode.com > mbcguitools 工具箱 matlab 源码程序 > mbcguitools/xregpersistfigpos.m

    function xregpersistfigpos(h,varargin)
%XREGPERSISTFIGPOS  Enable persistence of figure position across sessions
%
%  xregpersistfigpos(figH) enable figure position saving across MATLAB sessions.
%  This is achieved by saving the position on deletion into a database of positions
%  and persistence keys which is held in the preferences.  The next time this function
%  is called on the same persistence key, it will search for a saved position and use it
%  to initialise the figure.
%
%  Usage:
%  xregpersistfigpos(figH) sets up persistence, using the current position as the 
%  default, and the current tag as the persistence key.
%
%  xregpersistfigpos(figH,'key','KEYSTRING','DEFAULTPOS',POSITION) will use the given
%  key and default position instead.

%  Copyright 2000-2011 The MathWorks, Inc. and Ford Global Technologies, Inc.


IsPersistenceSetup = isprop(h, 'PositionPersistenceListener');
if IsPersistenceSetup
    return
end

key='';
defpos=[];

if nargin>1
   for n=1:2:length(varargin)
      switch lower(varargin{n})
      case 'key'
         key=varargin{n+1};
      case 'defaultpos'
         defpos=varargin{n+1};
      end
   end
end

if isempty(key)
   key=get(h,'Tag');
end
if isempty(defpos)
   defpos=get(h,'Position');
end

prfs=mbcprefs('mbc');
dbase=getpref(prfs,'WindowPositionPersistence');

if isempty(key)
   error(message('mbc:xregpersistfigpos:InvalidArgument'));
end

persistedpos=find( strcmp( key,dbase( :, 1 ) ) );
if isempty(persistedpos)
   dbase=[dbase; {key,defpos}];   
   setpref(prfs,'WindowPositionPersistence',dbase);
   set(h,'Position',defpos);
else
   set(h,'Position',dbase{persistedpos,2});
end

% attach a listener for the window closure
mbcgui.hgclassesutil.addprop(h, 'PositionPersistenceListener');
set(h,'PositionPersistenceListener',...
    mbcgui.hgclassesutil.listener(h,'ObjectBeingDestroyed',mbcutils.callback(@i_saveposition,key)));



function i_saveposition(h,~,key)
persistpos=get(h,'Position');

prfs=mbcprefs('mbc');
dbase=getpref(prfs,'WindowPositionPersistence');

keyindx=find( strcmp( key,dbase( :, 1 ) ) );
if isempty(keyindx)
   dbase=[dbase; {key,persistpos}];   
else
   dbase{keyindx,2}=persistpos;
end
setpref(prfs,'WindowPositionPersistence',dbase);