每次按下按钮时,我都应该随机更改三个标签的位置(例如: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/