Ever felt you’re being lied too? Well it just might be true…

Here’s an occasionally infuriating thing: if you set a form’s BorderStyle property to anything other than bsNone or bsSizeable, it won’t now report its real size and position when running on Vista or (I assume) Windows 7.

You can see this in effect on Vista at least if you set the form’s ScreenSnap property to True. Whereas the intended behaviour (and indeed, actual behaviour with the default frame style) is to snap to the edge of the screen, a form with a non-default border style will snap to just past the edge of the screen.

When I first discovered this issue soon after using Vista for the first time back in 2007, a bit of dead-end investigation left me assuming it to be down to some mysterious API/VCL conflict. Lo and behold however, but I’ve just discovered that it’s not that at all: for in reality, it’s actually a backward’s compatibility ‘feature’ on the part of Windows.

Anyhow, if you want to find the real size of a top-level window, you need to conditionally call a DWM (Desktop Window Manager) API function. Something like the following code should do —

uses Windows, DwmApi;

function GetRealWindowRect(Handle: HWND; var R: TRect): Boolean;
  Result := (GetParent(Handle) = 0) and DwmCompositionEnabled and
    (DwmGetWindowAttribute(Handle, DWMWA_EXTENDED_FRAME_BOUNDS, @R, SizeOf(R)) = S_OK);
  if not Result then
    Result := GetWindowRect(Handle, R);

Now this obviously won’t do anything about the size and positioning properties on TForm itself. If you need them to be accurate, it seems you must mark the EXE as requiring Vista or later in the PE header, after which Windows will no longer pretend to your application that its forms are slimmer than they actually are. As this causes the EXE to be unrunnable on XP or earlier, the cost is naturally rather large.

3 thoughts on “Ever felt you’re being lied too? Well it just might be true…

  1. Pingback: Setting up a custom title bar – reprise « Delphi Haven

  2. Hi Chris,
    I came across this issue a couple of days ago, too. Did you find a cure for this problem except limiting the app to Vista and upwards or choosing resizable borderstyles?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s