user2383818
user2383818

Reputation: 689

Delphi Getting control origin regarding form's left

I want to get the Left,Top coordinates of a control regarding to the container form. The target control may be, at the same time, inside of any number of other containers such as TPanels and TGroupBoxes. That means that to get the target control origin, the code should have to take into account the Left,Top coordinates of all the other containers + the Left,Top coordinates of the target control itself. Instead, I'm using a second approuch, wich consist in using the ClientToScreen function to get the Left,Top screen coordinates of the target control and after that, subtracting the Left,Top coordinates of the form. Saddly this approach is not working. I'm attaching an image that clarifies my thinkings and has the actual code I used to calculate the desired coordinates. I appreciate any help on this.enter image description here

Upvotes: 4

Views: 4309

Answers (3)

Martin Schneider
Martin Schneider

Reputation: 15388

So these 3 statements return the same, wanted TPoint:

aControl.ClientOrigin - aForm.ClientOrigin; 
aControl.ClientToParent(Point(0,0), aForm); 
aForm.ScreenToClient(aControl.ClientOrigin);

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 597941

@VitaliyG's answer shows how to convert the coordinates of the control's absolute top-left corner to Form-relative client coordinates. If you want to convert the coordinates of the top-left corner of the control's client area instead, you can pass the control's ClientOrigin property to the Form's ScreenToClient() method:

function GetControlClienOrigin(const aControl: TControl: const aForm: TForm): TPoint;
begin
  Result := aForm.ScreenToClient(aControl.ClientOrigin);
end;

If the control in question is a TWinControl descendant, an alternative is to use the Win32 API MapWindowPoints() function instead:

function GetControlClientOrigin(const aControl: TWinControl: const aForm: TForm): TPoint;
var
  Pt: TPoint;
begin
  Pt := Point(0, 0);
  SetLastError(0);
  if MapWindowPoints(aControl.Handle, aForm.Handle, Pt, 1) = 0 then
    CheckOSError(GetLastError);
  Result := Pt;
end;

Upvotes: 5

VitaliyG
VitaliyG

Reputation: 1857

Try using ClientToParent and specify form as Parent parameter.

You have to pass coords relative to control, so Top, Left of the control will be at control's (0,0)

Control.ClientToParent(TPoint.Create(0,0), Form)

Upvotes: 4

Related Questions