是否可以更改 ToolStripMenuItem 工具提示字体?

2023-11-24

我有一个动态填充的 ContextMenuStrip,其中每个 ToolStripMenuItem 都有一个工具提示的格式化文本。而且,为了使该文本对用户有意义,我必须使用等宽字体,例如“Courier New”。默认字体是常规的非等宽字体。 我找不到 ToolTip 对象的任何 getter,也找不到覆盖其 Draw 事件的方法,也找不到设置其样式的方法。

那么,是否可以更改 ToolStripMenuItem 的工具提示字体?

实现从 ToolTip 继承的 CustomToolTip 并不能解决问题,它将新的工具提示传递给 ToolStripMenuItem。


好的,感谢托尼·艾布拉姆斯 and 威廉·安德鲁斯,解决方法如下:

  • 已初始化的 ToolTip 的静态实例。

    toolTip = new ToolTip();
    toolTip.OwnerDraw = true;
    toolTip.Draw += new DrawToolTipEventHandler(tooltip_Draw);
    toolTip.Popup += new PopupEventHandler(tooltip_Popup);    
    toolTip.UseAnimation = true;
    toolTip.AutoPopDelay = 500;
    toolTip.AutomaticDelay = 500;
    
  • ToolTip 的 Popup 事件设置其大小。

    void tooltip_Popup(object sender, PopupEventArgs e)
    {
        e.ToolTipSize = TextRenderer.MeasureText(toolTipText, new Font("Courier New", 10.0f, FontStyle.Bold));
        e.ToolTipSize = new Size(e.ToolTipSize.Width + TOOLTIP_XOFFSET, e.ToolTipSize.Height + TOOLTIP_YOFFSET);
    }
    
  • ToolTips 实际绘制的绘制事件。

    void tooltip_Draw(object sender, DrawToolTipEventArgs e)
    {
    Rectangle bounds = e.Bounds;
    bounds.Offset(TOOLTIP_XOFFSET, TOOLTIP_YOFFSET);
    DrawToolTipEventArgs newArgs = new DrawToolTipEventArgs(e.Graphics, e.AssociatedWindow, e.AssociatedControl, bounds, e.ToolTipText, toolTip.BackColor, toolTip.ForeColor, new Font("Courier New", 10.0f, FontStyle.Bold));
        newArgs.DrawBackground();
        newArgs.DrawBorder();
        newArgs.DrawText(TextFormatFlags.TextBoxControl);
    }
    
  • ToolStripMenuItem 的 MouseEnter 事件显示工具提示。

    System.Windows.Forms.ToolStripMenuItem item = (sender as System.Windows.Forms.ToolStripMenuItem);
    toolTip.SetToolTip(item.Owner, "ToolTipText");
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否可以更改 ToolStripMenuItem 工具提示字体? 的相关文章

随机推荐