【问题标题】:c# change Label (Control) location at runtimec# 在运行时更改标签(控件)位置
【发布时间】:2014-10-07 13:45:11
【问题描述】:

默认工具提示对我来说效果不佳,因此我使用标签控件及其“Visible”属性制作了一个自定义工具提示,作为按下键时的错误弹出窗口。所以现在我正在尝试动态设置标签的位置,在我的例子中是一个文本框的位置,但它总是显示在表单的左上角。

方法如下:

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

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

【问题讨论】:

  • 我猜targetControl.Location 是控件在其容器内的位置(即不相对于窗口)?
  • @DavidG:是的,它是主窗体中控件的位置,我希望标签出现在该位置。
  • 我是说,targetControl 是否存在于另一个控件(如选项卡视图或面板)中? Location 属性总是相对于它的容器,而不是表单。
  • 哦,好吧,它存在于一个拆分容器中。那我该如何设置标签的位置呢?

标签: c# dynamic location label


【解决方案1】:

问题是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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多