【问题标题】:Positioning controls in different containers relative to each other相对于彼此在不同容器中定位控件
【发布时间】:2013-07-12 08:27:20
【问题描述】:

我有以下情况,我想将Button1 定位在正下方并与Button 2 水平对齐,但仍将Button1 保留在groupBox1 中,而Button 2 在@987654327 中@:

我看过几篇关于 PointToClient()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

【问题讨论】:

  • 我很困惑right below and horizontally aligned。图像是否应该是最终结果,并且在调整窗口大小后两个按钮的比例相同?还是说按钮重叠?
  • 不,该图像是它可能看起来像开始的示例。重新定位后,按钮 1 应该出现在 groupBox2 中,并且在按钮 2 下方。代码不完整 - 只是我尝试过的一些事情的一部分,以便让按钮以这样的方式定位彼此更相关(与其不同的父容器相关)。
  • 我仍然不确定你想要的输出。但我觉得可以通过操纵 Anchor 属性本身来实现。我猜不需要那么多代码。

标签: c# winforms


【解决方案1】:

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

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

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

//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));
}

【讨论】:

  • 谢谢,最后一个选项似乎或多或少是我需要的。
【解决方案2】:

您可以通过考虑不同的相对位置来仅依赖 .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;
}

【讨论】:

  • 谢谢,但这是我想避免的,因为在我的实际应用中,事情会稍微复杂一些,并且可能有多层容器,使得这样的计算有点混乱。
  • 这种实现可能会变得困难(主要是在复杂的情况下),但它们无疑提供了最可靠的性能。但好吧......这取决于你。
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多