简体   繁体   中英

c# change Label (Control) location at runtime

The default tooltip isn't working well for me, so I made a custom tooltip using a Label Control and its 'Visible' property as an error Popup when a key is pressed. So now I'm trying to set the position of the label dynamically, in my case to the location of a textBox, but it always shows up in the upper left corner of the form.

Here's the method:

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

How can I accomplish this? Thanks!

The problem is that Control.Location gives your position within the current container. You just need to get the absolute location of the control with respect to the form like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM