csharp 控件根据窗体大小自动调整所在坐标
时间: 2023-09-13 22:03:24 浏览: 45
可以通过窗体的 Resize 事件来实现控件根据窗体大小自动调整所在坐标的功能。具体步骤如下:
1. 在窗体的 Resize 事件中,获取窗体的大小和控件的初始位置。
```
private void Form1_Resize(object sender, EventArgs e)
{
int formWidth = this.ClientSize.Width;
int formHeight = this.ClientSize.Height;
int controlX = myControl.Location.X;
int controlY = myControl.Location.Y;
}
```
2. 根据窗体的大小和控件的初始位置计算出控件应该调整到的新位置。
```
int newControlX = (int)((double)controlX / oldFormWidth * formWidth);
int newControlY = (int)((double)controlY / oldFormHeight * formHeight);
```
3. 将控件的位置设置为计算出的新位置。
```
myControl.Location = new Point(newControlX, newControlY);
```
完整的代码示例:
```
private int oldFormWidth;
private int oldFormHeight;
private void Form1_Load(object sender, EventArgs e)
{
oldFormWidth = this.ClientSize.Width;
oldFormHeight = this.ClientSize.Height;
}
private void Form1_Resize(object sender, EventArgs e)
{
int formWidth = this.ClientSize.Width;
int formHeight = this.ClientSize.Height;
int controlX = myControl.Location.X;
int controlY = myControl.Location.Y;
int newControlX = (int)((double)controlX / oldFormWidth * formWidth);
int newControlY = (int)((double)controlY / oldFormHeight * formHeight);
myControl.Location = new Point(newControlX, newControlY);
oldFormWidth = formWidth;
oldFormHeight = formHeight;
}
```