Search code examples
windowsdelphi

How to center a Delphi form on a 4k screen? (Windows scaling enabled) - poScreenCenter not working


I have a Delphi form functioning as a sort of splash screen (i.e. borderless) that I want to appear exactly in the center of the (main) screen (currently using TForm1.Position := poScreenCenter to achieve this).

This is not working on 4k monitors with scaling (or any screen really that uses a percentage higher than 100% in Windows (Settings > Display > Scale and Layout)). In such cases, the form will pop up more in the upper left-hand corner rather than the exact middle of the screen. This seems like a HiDPI-related bug in Delphi, as the program looks otherwise fine and works well.

My guess is that I would have to set TForm1.Position to poDesigned and manually set TForm1.Top and Left in the OnShow event. The question is: To what? What would be a universal solution to ensure that the form always appears in the exact screen center, regardless of monitor size / resolution / scaling etc. I have stumbled across a function called "muldiv" that may be of help but I am unsure how to use it.

I have:

  • Delphi 10.3 Version 26.0.36039.7899
  • Windows 10 Version 20H2
  • DPI awareness (Project > Options > Application > Manifest) set to "System Aware"
  • TForm1.Scaled set to "True"
  • TForm1.PixelsPerInch set to "96"
  • TForm1.FormStyle set to "fsStayOnTop"
  • TForm1.BorderStyle set to "bsNone"
  • TForm1.Position set to "poScreenCenter"
  • TFrom1.DefaultMonitor set to "dmActiveForm"
  • TForm1.Width and Height both set to "480"

Thanks for your help.


Solution

  • To center the form, use this code:

    Form1.Left := (Form1.Monitor.Width  - Form1.Width)  div 2;
    Form1.Top  := (Form1.Monitor.Height - Form1.Height) div 2;
    

    Of course you may check that the form is not bigger than the monitor.