Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

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

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 the right edge of the textbox, so I tried to move the message left by message length.

So I tried to get the string length by using TextRenderer.MeasureText(), but the position is a little bit off as shown below.

current result

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.DefaultFont, textBox1.Size, TextFormatFlags.LeftAndRightPadding).Width;
   int toolTipTextPosition_X = textBox1.Size.Width - textWidth;

   myToolTip.Show(test, textBox1, toolTipTextPosition_X, textBox1.Size.Height);
}

I tried with different flags in the MeasureText() function but it didn't help, and since ToolTip message has a padding, I went for TextFormatFlags.LeftAndRightPadding.

To be clear, this is what I would like to achieve:

desired output

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set OwnerDraw property of the ToolTip to true. Then you can control appearance and location of the tooltip in Draw event. In the following example, I've found the tooltip handle and moved it to the desired location using MoveWindow Windows API function :

[System.Runtime.InteropServices.DllImport("User32.dll")]
static extern bool MoveWindow(IntPtr h, int x, int y, int width, int height, bool redraw);
private void toolTip1_Draw(object sender, DrawToolTipEventArgs e)
{
    e.DrawBackground();
    e.DrawBorder();
    e.DrawText();
    var t = (ToolTip)sender;
    var h = t.GetType().GetProperty("Handle",
      System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    var handle = (IntPtr)h.GetValue(t);
    var c = e.AssociatedControl;
    var location = c.Parent.PointToScreen(new Point(c.Right - e.Bounds.Width, c.Bottom));
    MoveWindow(handle, location.X, location.Y, e.Bounds.Width, e.Bounds.Height, false);
}

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...