获取表单的坐标

本文关键字:坐标 表单 获取 | 更新日期: 2023-09-27 18:11:07

我想知道,你如何得到一个形式的坐标?

我有一个应用程序,目前有一个按钮。此按钮随机每1秒重新定位一次。但是,我希望这个按钮总是在表单内重新定位-而不是在表单的边界之外。所以,我想我应该找到的形式的界限,并使用,以确保按钮总是在形式的界限内。我如何得到的高度和宽度的形式?

我有以下代码工作(但用户的屏幕大小不是我想要的):

int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
int screenWidth = Screen.PrimaryScreen.WorkingArea.Width;

这段代码不应该工作吗?

int xPosition = position.X;
int yPosition = position.Y; 
int num = random.Next(screenHeight);
int num1 = random.Next(screenWidth);
Point templocation;
templocation = new Point(num1, num);

ClickMe.Location = templocation;
templocation.X = num1;
templocation.Y = num; 

任何帮助都将非常感激。

p。我已经查看了这个网站http://msdn.microsoft.com/en-us/library/system.windows.forms.control.resize(v=vs.71).aspx,但行"控制控制=(控制)发送者;"产生一个错误…

获取表单的坐标

更新后,这里是新的答案:

当你定位你的按钮时,你必须确保不要超出表单的边界。所以你的按钮的左边位置在

之间
int leftMin = 0;
int leftMax = myForm.ClientSize.Width - myButton.Width;

按钮的顶部位置

int topMin = 0;
int topMax = myForm.ClientSize.Height - myButton.Height;

对于你的例子:

private void timer1_Tick(object sender, EventArgs e)
{
    Random random = new Random();
    int x = random.Next(0, ClientSize.Width - button1.Width);
    int y = random.Next(0, ClientSize.Height - button1.Height);
    button1.Location = new Point(x, y);
}

旧答案…

如果要查找当前窗体在屏幕上的位置:

int xPosition = this.Location.X;    
int yPosition = this.Location.Y;

Point position = this.Location;

虽然Location在form构造函数中为" 0,0 "

使用表单的位置(类型为Point):

this.Location

(用这个代替Form1)

:

this.Height
this.Width

Location属性为您提供"以屏幕坐标表示表单左上角的点"。

对于宽度和高度,使用

form.Size.Width
form.Size.Height