How to align right edges of a control and ToolTip Message in C#

前端 未结 2 2035
难免孤独
难免孤独 2020-12-20 23:15

I want to display a ToolTip message below a TextBox, but also want them to be right aligned.

I was able to position the ToolTip message at

2条回答
  •  囚心锁ツ
    2020-12-20 23:54

    The ToolTip font is bigger than SystemFonts.DefaultFont so the measurement is incorrect. I don't know what is the exact variable for the ToolTip font, but many of the other SystemFonts are configured to Segoe UI/size 9, which the Tooltip font in my PC. In addition, you have to add 6px for the padding.

    private void button1_Click(object sender, EventArgs e)
    {
        ToolTip myToolTip = new ToolTip();
    
        string test = "This is a test string.";
        int textWidth = TextRenderer.MeasureText(test, SystemFonts.CaptionFont, textBox1.Size, TextFormatFlags.LeftAndRightPadding).Width;
        textWidth += 6;
        int toolTipTextPosition_X = textBox1.Size.Width - textWidth;
    
        myToolTip.Show(test, textBox1, toolTipTextPosition_X, textBox1.Size.Height);
    }
    

    For perfect control you could draw the tooltip yourself with Tooltip.OwnerDraw and the event Tooltip.Draw, choosing font, padding and appearance.

提交回复
热议问题