c# - 如何获取标签的位置?

标签 c# winforms position label

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

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

最佳答案

使用获取值

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)。请注意,您还应该检查窗口的宽度和高度,并减去标签的宽度和高度,以免超出窗口边界。

关于c# - 如何获取标签的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694014/

相关文章:

c# - 当有绑定(bind)导航器时,如何在设计时停止 winforms 中的 datagridview 自动生成列?

html - 在绝对 div 中使用 Z-index 和定位文本来创建水印

css - position:absolute !important 在 Firefox 中不起作用

javascript - 相对于整个屏幕在 iframe 内保持固定位置

c# - 使用哈希表查找字符串中的字符

c# - 将常量呈现到 XML 文档中?

.net - WM_CLOSE 和 SC_CLOSE 之间的区别

.net - 在 WinForms 中向系统菜单(左上角图标菜单)添加条目?

c# - XNA查找玩家最近的向量

c# - 正则表达式:保留未知子字符串