【问题标题】:How can I get the position of a label?如何获得标签的位置?
【发布时间】:2013-12-20 09:40:28
【问题描述】:

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

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

【问题讨论】:

  • 这是winforms吗? ASP.NET ? wpf ?
  • @MauricioGracia winforms
  • 表格上的标签是固定位置的,你只是交换它们的顺序吗?
  • @Brian 是的,没错

标签: c# winforms position label


【解决方案1】:

使用获取值

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);
    }
}

然后只需使用随机化器将值设置为 Point(x, y)。请注意,您还应该检查窗口的宽度和高度,并减去标签的宽度和高度,以免超出窗口边界。

【讨论】:

    【解决方案2】:

    您可以访问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

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

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

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

    【讨论】:

    • Bounds 给出了位置,但你实际上不能用这些来移动控件。您必须将 Location 设置为新点或更改 Label.Left 和 Label.Top。
    【解决方案3】:
    Label.Left, Label.Top
    

    Location 只是一个不能修改的 Point 结构体。

    【讨论】:

      猜你喜欢
      • 2019-02-25
      • 2018-06-30
      • 2018-07-13
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多