Bar*_*kut 5 .net c# alignment tooltip winforms
我想在a ToolTip
下方显示一条消息TextBox
,但也希望它们是正确对齐的.
我能够将ToolTip消息放在文本框的右边缘,所以我尝试按消息长度移动消息.
所以我尝试使用TextRenderer.MeasureText()来获取字符串长度,但是位置有点偏,如下所示.
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);
}
Run Code Online (Sandbox Code Playgroud)
我尝试在MeasureText()函数中使用不同的标志,但它没有帮助,因为ToolTip消息有填充,我去了TextFormatFlags.LeftAndRightPadding.
要清楚,这就是我想要实现的目标:
您可以将的OwnerDraw
属性设置ToolTip
为true。然后您可以控制工具提示的外观和位置Draw
。在以下示例中,我找到了工具提示句柄,并使用MoveWindow
Windows 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);
}
Run Code Online (Sandbox Code Playgroud)