我想在ToolTip下面显示TextBox消息,但也希望它们是右对齐的。
我可以将工具提示消息放置在文本框的右边缘,因此我尝试按消息长度将消息向左移动。
所以我尝试使用textRenderer.measureText()来获取字符串的长度,但是位置有点偏离,如下所示。
c# - 如何在C#中对齐控件和工具提示消息的右边缘-LMLPHP

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

我试过在measureText()函数中使用不同的标志,但没有帮助,因为工具提示消息有一个填充,所以我选择了textformatflags.leftandrightpadding。
明确地说,这是我想要实现的目标:
c# - 如何在C#中对齐控件和工具提示消息的右边缘-LMLPHP

最佳答案

您可以将OwnerDrawToolTip属性设置为true。然后可以在Draw事件中控制工具提示的外观和位置。在下面的示例中,我找到了工具提示句柄,并使用MoveWindowwindows api函数将其移动到所需位置:

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

c# - 如何在C#中对齐控件和工具提示消息的右边缘-LMLPHP

07-24 09:44
查看更多