首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ToolTip中对齐控件的右边和C#消息

如何在ToolTip中对齐控件的右边和C#消息
EN

Stack Overflow用户
提问于 2016-12-24 15:46:36
回答 2查看 1.9K关注 0票数 5

我希望在ToolTip下面显示一个TextBox消息,但也希望它们对齐。

我能够将ToolTip消息定位在文本框的右侧,因此我尝试移动消息长度所留下的消息。

因此,我尝试使用TextRenderer.MeasureText()获取字符串长度,但是位置有点偏离,如下所示。

代码语言:javascript
复制
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()函数中使用不同的标志,但是没有帮助,而且由于ToolTip消息有一个填充,所以我选择了TextFormatFlags.LeftAndRightPadding。

明确地说,这就是我想要达到的目标:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-24 16:58:20

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

代码语言:javascript
复制
[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);
}

票数 6
EN

Stack Overflow用户

发布于 2016-12-24 17:01:29

ToolTip字体比SystemFonts.DefaultFont字体大,所以测量不正确。我不知道ToolTip字体的确切变量是什么,但其他许多SystemFonts被配置为Segoe /size 9,这是我的PC中的工具提示字体。此外,您还必须为填充添加6px。

代码语言:javascript
复制
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);
}

为了实现完美的控制,您可以使用Tooltip.OwnerDraw和事件Tooltip.Draw自行绘制工具提示,选择字体、填充和外观。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41314678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档