c#在运行时更改标签(控件)位置

时间:2014-10-07 13:45:11

标签: c# dynamic location label

默认工具提示对我来说效果不佳,所以我在按下某个键时使用Label Control及其“Visible”属性作为错误Popup进行了自定义工具提示。所以现在我试图动态设置标签的位置,在我的情况下设置为textBox的位置,但它总是显示在表单的左上角。

以下是方法:

    void ShowCustomToolTip(string text, Control targetControl, int duration = 1000, int x = 0, int y = 0)
    {
        customToolTip.Text = text;
        customToolTip.Visible = true;

        // the crucial line that needs to be changed, I guess
        customToolTip.Location = new Point(targetControl.Location.X + x, targetControl.Location.Y + y);

        Set.Timer(duration);
        customToolTip.Hide();
    }

我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分:2)

问题是Control.Location给出了你在当前容器中的位置。你只需要获得控件的绝对位置,就像这样:

void ShowCustomToolTip(string text, Control targetControl, int duration = 1000, int x = 0, int y = 0)
{
    customToolTip.Text = text;
    customToolTip.Visible = true;

    Point absoluteLocation = targetControl.FindForm().PointToClient(
        targetcontrol.Parent.PointToScreen(control.Location));

    // the crucial line that needs to be changed, I guess
    customToolTip.Location = new Point(absoluteLocation.X + x, absoluteLocation.Y + y);

    Set.Timer(duration);
    customToolTip.Hide();
}