Guardar (y cargar) la posición, tamaño y estado del formulario

4461 vistas

Para realizar esta tarea de guardar (y cargar) la posición, tamaño y estado del formulario, nos vasaremos en el registro de Windows.

Veamos las dos funciones necesarias

Función de recuperación del estado



delphi
  1. procedure RecallWin(Form:TForm);
  2. var
  3.   Registro: TRegistry;
  4. begin
  5.   Registro := TRegistry.Create;
  6.   Registro.OpenKey('\Software\' + ExtractFileName(Application.Exename) + '\WinPos', True);
  7.   if Registro.ValueExists(Form.Name) then
  8.   begin
  9.     if (Registro.ReadInteger(Form.Name + '_ScrWidth') = Screen.Width) or
  10.       (Registro.ReadInteger(Form.Name + '_ScrHeight') = Screen.Height) then
  11.     begin
  12.       case Registro.ReadInteger(Form.Name + '_WindowState') of
  13.         1: Form.WindowState := wsNormal;
  14.         2: Form.WindowState := wsMinimized;
  15.         3: Form.WindowState := wsMaximized;
  16.       end;
  17.       if Form.WindowState<>wsMaximized then
  18.       begin
  19.         Form.Top := Registro.ReadInteger(Form.Name + '_Top');
  20.         Form.Left := Registro.ReadInteger(Form.Name + '_Left');
  21.         Form.Width := Registro.ReadInteger(Form.Name + '_Width');
  22.         Form.Height := Registro.ReadInteger(Form.Name + '_Height');
  23.       end;
  24.     end;
  25.   end;
  26.   Registro.Free;
  27. end;



Función de grabación del estado



delphi
  1. procedure MemoWin(Form:TForm);
  2. var
  3.   Registro: TRegistry;
  4. begin
  5.   Registro := TRegistry.Create;
  6.   Registro.OpenKey('\Software\ + ExtractFileName(Application.Exename) + \WinPos', True);
  7.   Registro.WriteInteger(Form.Name + '_ScrWidth', Screen.Width);
  8.   Registro.WriteInteger(Form.Name + '_ScrHeight', Screen.Height);
  9.   case Form.WindowState of
  10.     wsNormal: Registro.WriteInteger(Form.Name + '_WindowState', 1);
  11.     wsMinimized: Registro.WriteInteger(Form.Name + '_WindowState', 2);
  12.     wsMaximized: Registro.WriteInteger(Form.Name + '_WindowState', 3);
  13.   end;
  14.   Registro.WriteInteger(Form.Name + '_Width', Form.Width);
  15.   Registro.WriteInteger(Form.Name + '_Height', Form.Height);
  16.   Registro.WriteInteger(Form.Name + '_Left', Form.Left);
  17.   Registro.WriteInteger(Form.Name + '_Top', Form.Top);
  18.   Registro.WriteBool(Form.Name, True);
  19.   Registro.Free;
  20. end;



Ahora sólo nos quedará hacer la llamada respectiva en el OnCreate y en el OnDestroy del formulario



delphi
  1. procedure TForm1.FormCreate(Sender: TObject);
  2. begin
  3.   RecallWin(Form1);
  4. end;
  5.  
  6. procedure TForm1.FormDestroy(Sender: TObject);
  7. begin
  8.   MemoWin(Form1);
  9. end;



También podrÃa implementarse para que, en lugar de grabar en el registro de Windows, grabase la información en un fichero Ini.

Nota: añadir Registry en el uses del formulario