我怎样才能获得标签的位置?

时间:2013-12-20 00:00:00

标签: c# winforms position label

每当我按下按钮时,我应该随机改变三个标签的位置(例如:label1将在label2的位置)。

所以我决定取标签的位置并将它们存储在一个数组中。但是,我不知道如何获得标签的位置。我试着说double position = label1.location.X;,但它不起作用。

3 个答案:

答案 0 :(得分:3)

使用

获取值
label1.Left, label1.Top

使用

设置值
label1.Location = new Point(x, y);

不要忘记包含

using System.Windows.Forms;
using System.Drawing; // to use System.Drawing.Point(Label.Left, Label.Top)

我写过代码,希望能帮助你理解这些代码。 单击标签以获取其坐标。

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

class LabelForm : Form
{
    Label label1;
    //
    public LabelForm()
    {
        label1 = new Label();
        label1.Text = "ClickMe";
        label1.Location = new Point(10, 10); // This is the place where you set the location of your label. Currently, it is set to 10, 10.
        label1.Click += new EventHandler(labelClick);
        Controls.Add(label1);
    }
    //
    static void Main(string[] args)
    {
        LabelForm lf = new LabelForm();
        Application.Run(lf);
    }
    //
    protected void labelClick(object o, EventArgs e)
    {
        // This is how you can get label's positions
        int left = label1.Left;
        int top = label1.Top;
        MessageBox.Show("Left position of the label: " + left
            + "\nTop position of the label: " + top,
            "", MessageBoxButtons.OK);
    }
}

然后使用randomizer将值设置为Point(x,y)。请注意,您还应检查窗口的宽度和高度,并减去标签的宽度和高度,使其不超出窗口边框。

答案 1 :(得分:1)

您可以访问Bounds属性,它是Rectangle类型的对象,它具有组件的宽度,高度和x,y坐标。

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.bounds(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/system.drawing.rectangle(v=vs.110).aspx

假设您正在使用winform类Label

编辑:一个更简单的属性是位置

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.location(v=vs.110).aspx

如果您只查看Label的msdn文档,您会发现有很多方法可以获取这些数据。

答案 2 :(得分:1)

Label.Left, Label.Top

位置只是一个无法修改的Point结构。