I find myself in a tricky situation here, I have an application that has a form embedded in a form, embedded in a form, embedded in a form... (you got the picture).

I'm trying to find the middle of one of the forms (that was easy (Self.Width div 2) and (Self.Height div 2), right). Then the position relative to the screen (that was easy as well (Self.Width div 2) + Self.Left and (Self.Height div 2) + Self.Top).

The problem is that this form is embedded in another form so I got (Self.Width div 2) + Self.Left + Self.Parent.Left and (Self.Height div 2) + Self.Top + Self.Parent.Top

The problem is that I have 6 to 8 forms embedded in one another. I'm thinking a recursive call; the problem is that not all objects are forms, they are a mix of forms, tabs, panel, etc.

What would be an elegant way to solve it?

有帮助吗?

解决方案

How about this one:

FUNCTION CenterOfFormAsScreenCoords(F : TForm) : TPoint;
  BEGIN
    Result:=F.ClientToScreen(Point(0,0));
    Result:=Point(Result.Left+F.Width DIV 2,Result.Top+F.Height DIV 2)
  END;

or a combined version, as suggested by Remy Lebeau:

FUNCTION CenterOfFormAsScreenCoords(F : TForm) : TPoint;
  BEGIN
    Result:=F.ClientToScreen(Point(F.Width DIV 2,F.Height DIV 2))
  END;

and a more general version (as suggested by Craig Young):

FUNCTION GetCenterOfControlAsScreenCoords(C : TControl) : TPoint;
  BEGIN
    Result:=C.ClientToScreen(Point(C.Width DIV 2,C.Height DIV 2))
  END;

or as a CLASS HELPER:

TYPE
  TControlHelper = CLASS HELPER FOR TControl
                     FUNCTION CenterAsScreenCoords : TPoint;
                   END;

FUNCTION TControlHelper.CenterAsScreenCoords : TPoint;
  BEGIN
    Result:=ClientToScreen(Point(Width DIV 2,Height DIV 2))
  END;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top