1

我有以下情况,我想定位Button1在正下方并水平对齐到Button 2,但仍然保持Button1groupBox1,而Button 2groupBox2

在此处输入图像描述

我看过几篇关于PointToClient()and的帖子PointToScreen(),但仍然无法在不同的容器之间正确翻译——groupBox1groupBox2这种情况下。

我已经尝试了以下代码的一些变体(例如,在调整表单大小时尝试重新定位按钮),但我仍然对它的工作原理感到困惑。

具体来说,我似乎不清楚control我应该调用PointToScreen()哪个,以及我应该将哪些参数传递给该方法以实现我上面描述的内容。

private void Form1_Paint(object sender, PaintEventArgs e)
{  
    var btn2Pos = button2.PointToScreen(button2.Location);

    button1.Location = button1.PointToClient(btn2Pos);
}

解决这个问题的最简单方法是什么?

旁注,这样做的原因
我希望能够禁用groupBox2,以及其中的所有控件,但仍保留某些控件,例如button 1启用,即使它们相对于button 2.

4

3 回答 3

1

我认为您不需要在这里使用PointToClientPointToScreen

//This will place button1 over button2
button1.Left = groupBox2.Left + button2.Left;
button1.Top = groupBox2.Top + button2.Top;

如果你想使用PointToClientand PointToScreen,你可以这样做:

//The code should be placed in Form load, if placing in form Constructor, the result may be not expected.
private void Form1_Load(object sender, EventArgs e){ 
  //This will place button1 over button2
  button1.Location = groupBox1.PointToClient(groupBox2.PointToScreen(button2.Location));
}
于 2013-07-12T08:50:41.133 回答
0

您可以通过考虑不同的相对位置来仅依赖 .Left/.Top 属性。例子:

button1.Location = positining(button1);

通过在这些行上调用函数:

private Point positining(Button curButton)
{
    Point outPoint = new Point();

    if(curButton == button1)
    {
        outPoint.X = groupBox2.Left + button2.Right + 20;
        outPoint.Y = groupBox2.Top + button2.Bottom - 20;
    }
    else if (curButton == button2)
    {
        outPoint.X = groupBox2.Left + button1.Left - 20 - button2.Width;
        outPoint.Y = groupBox2.Top + button1.Top + 20 + button2.Height;
    }

    return outPoint;
}
于 2013-07-12T09:00:09.480 回答
0

我很欣赏这里的答案,但最终还是按照同事的建议使用了以下解决方案:

我创建了另一个,第三个容器,但是这个没有边框。该容器完全重叠groupBox2,并button1位于该容器内,因此相对于它。

由于新容器的点 (0 , 0) 与 中的等效点重叠,因此任一容器中groupBox2具有相同坐标的任何控件都将定位在同一位置,我需要做的就是确保调用BringToFront()(和/或SendToBack()如果需要)以确保控件正确显示。

于 2013-07-14T08:56:53.863 回答