|
Delphi Tips and Tutorials
Tip #2: Saving the position and size of a window between instances
If you want to save the position of your window so that it starts up in the same place as
when the user closed it down, the following code will save the window position to the registry. You could put
a call to SaveFormPositionToRegistry in the FormDestroy event of your main form. Change the
registry key to something more appropriate to your application.
procedure TfrmExample.SaveFormPositionToRegistry;
var
r: TRegistry;
begin
r := TRegistry.Create;
try
r.RootKey := HKEY_CURRENT_USER;
if r.OpenKey('\Software\darnkitty.com\Example\Options', True) then
begin
r.WriteInteger('PosTop', Top);
r.WriteInteger('PosLeft', Left);
r.WriteInteger('PosWidth', Width);
r.WriteInteger('PosHeight', Height);
r.CloseKey;
end;
finally
r.Free;
end;
end;
The following code will read in the saved values and position the window in the correct place.
Once again, change the registry key to something more appropriate to your application.
procedure TfrmExample.LoadFormPositionFromRegistry;
var
r: TRegistry;
begin
r := TRegistry.Create;
try
r.RootKey := HKEY_CURRENT_USER;
r.Access := KEY_READ;
if r.OpenKey('\Software\darnkitty.com\Example\Options', False) then
begin
try
Top := r.ReadInteger('PosTop');
Left := r.ReadInteger('PosLeft');
Width := r.ReadInteger('PosWidth');
Height := r.ReadInteger('PosHeight');
except
end;
r.CloseKey;
end;
finally
r.Free;
end;
end;
You would put a call to LoadFormPositionFromRegistry in the FormCreate event of
your main form. Remember also to add the Registry unit to the uses clause in your form or else
the code will not compile.
Note that there is a try..except block around the ReadIntegers. This is to cover the chance that
the key exists and is successfully opened, but the four integers do not exist yet (this may happen the first time the
user runs the application). Since this is purely a cosmetic procedure, in my opinion, there is no need to re-raise
any exception or otherwise do anything with it.
|