Mirror

Resolution independent applications (Views: 101)


Problem/Question/Abstract:

Have you ever wondered how to display your forms and components always the same size no matter what the screen resolution is?

Answer:

You have to modify your projectīs DPR file to acomplish that:

// Modify your projects code to achieve resolution independent
// applications. I have found that this trick only works for
// resolutions greater than the resolution you design the forms, for
// example if you design at 800x600 you can use your application at
// a resolution of 1024 x 768 or greater.
// However it wonīt run fine at 640x480 (altough, nowadays I donīt
// kwonw many people with thatv resolution, so I think 800X600 is
// fine)

program TestResolution;

uses
  Forms,
  Dialogs,
  Classes,
  TypInfo,
  Windows,
  Unit1 in 'Unit1.pas' {Form1},
  Unit2 in 'Unit2.pas' {Form2};

{$R *.RES}

const
  //If form is designed in 800 x 600 mode
  ScreenWidth: LongInt = 800;
  ScreenHeight: LongInt = 600;

var
  vi_Counter1, vi_Counter2: Integer;
  NewFormWidth: Integer;

begin
  Application.Initialize;
  Application.CreateForm(TForm1, Form1);
  Application.CreateForm(TForm2, Form2);
  NewFormWidth := GetSystemMetrics(0);

  with Application do
    for vi_Counter1 := 0 to ComponentCount - 1 do
    begin
      //Find all the Auto-create forms
      if Components[vi_Counter1] is TForm then
        with (Components[vi_Counter1] as TForm) do
        begin
          Scaled := True;
          if screen.Width <> ScreenWidth then
          begin
            Height := longint(Height) * longint(screen.Height) div
              ScreenHeight;
            Width := longint(Width) * longint(screen.Width) div
              ScreenWidth;
            ScaleBy(screen.Width, ScreenWidth);

            //Now Scale the Formīs componentīs Font
            for vi_Counter2 := 0 to ControlCount - 1 do
              with Components[vi_Counter2] do
                //Use RTTI information to find for a Font property
                if GetPropInfo(ClassInfo, 'font') <> nil then
                  Font.Size := (NewFormWidth div ScreenWidth)
                    * font.Size;
          end;
        end;
    end;
  Application.Run;
end.

finally some aditional considerations:

You will have to scale every form create on the fly.
Use only TrueType fonts, not Bitmapped fonts to avoid problems.
Donīt set the Formīs Position property to poDesigned, when scalling it could be off the screen.
Don't change the PixelsPerInch property of the form.
Don't crowd controls on the form - leave at least 4 pixels between controls, so that a one pixel change in border  locations (due to scaling) won't show up as ugly overlapping  controls.

<< Back to main page