簡體   English   中英

如何獲取控件相對於其窗體位置的位置?

[英]How do I get a control's location relative to its Form's location?

我正在尋找一個屬性,它為我提供了一個控件相對於其窗體位置的位置,而不是窗體的ClientRectangle's “0,0”。

當然我可以將所有內容轉換為屏幕坐標,但我想知道是否有更直接的方法來做到這一點。

您需要轉換為屏幕坐標,然后做一些數學運算。

Point controlLoc = form.PointToScreen(myControl.Location);

表單的位置已經在屏幕坐標中。

現在:

Point relativeLoc = new Point(controlLoc.X - form.Location.X, controlLoc.Y - form.Location.Y);

這將為您提供相對於窗體左上角的位置,而不是相對於窗體客戶區的位置。

我認為這將回答您的問題。 請注意,“this”是形式。

Rectangle screenCoordinates = control.Parent.ClientToScreen(control.ClientRectangle);
Rectangle formCoordinates = this.ScreenToClient(screenCoordinates);

似乎答案是沒有直接的方法可以做到這一點。

(正如我在我要找的不是使用屏幕坐標以外的方式問題說明。)

鑒於問題的具體情況,所選答案在技術上是正確的:.NET 框架中不存在此類屬性。

但是如果你想要這樣的屬性,這里有一個控件擴展可以解決這個問題。 是的,它使用屏幕坐標,但考慮到帖子標題的一般性質,我相信登陸此頁面的一些用戶可能會覺得這很有用。

順便說一句,我花了幾個小時試圖通過循環所有控件父控件來在沒有屏幕坐標的情況下執行此操作。 我永遠無法調和這兩種方法。 這很可能是由於 Hans Passant 對 OP 的評論有關 Aero 對窗口大小的影響。

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Cambia
{
    public static class ControlExtensions
    {
        public static Point FormRelativeLocation(this Control control, Form form = null)
        {
            if (form == null)
            {
                form = control.FindForm();
                if (form == null)
                {
                    throw new Exception("Form not found.");
                }
            }

            Point cScreen = control.PointToScreen(control.Location);
            Point fScreen = form.Location;
            Point cFormRel = new Point(cScreen.X - fScreen.X, cScreen.Y - fScreen.Y);

            return cFormRel;

        }

    }
}

當您在許多其他控件中將 Autosize 設置為 true 時,上面的答案都沒有幫助,即

Form -> FlowLayoutPanel -> Panel -> Panel -> Control

所以我用不同的邏輯編寫了自己的代碼,我只是不知道如果在父控件之間使用一些對接會產生什么結果。 我想 Margins 和 Paddings 需要參與這種情況。

    public static Point RelativeToForm(this Control control)
    {

        Form form = control.FindForm();
        if (form is null)
            return new Point(0, 0);

        Control parent = control.Parent;

        Point offset = control.Location;            

        while (parent != null)
        {
            offset.X += parent.Left;
            offset.Y += parent.Top;                
            parent = parent.Parent;
        }

        offset.X -= form.Left;
        offset.Y -= form.Top;

        return offset;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM