【问题标题】:Is there a way to determine if a form's text will fit in?有没有办法确定表单的文本是否适合?
【发布时间】:2015-07-28 08:38:42
【问题描述】:

有没有办法使用表单的当前宽度来确定表单的文本属性是否适合顶栏(或者是否会被“...”截断)?

【问题讨论】:

标签: c# vb.net forms winforms


【解决方案1】:

你可以看看TextRenderer.MeasureText()

要计算标题文本的宽度,请使用以下 sn-p:

var width = TextRenderer.MeasureText(caption, SystemFonts.CaptionFont).Width;

您可以使用表单的大小,减去图标(如果可见)和右上角的按钮(取决于操作系统版本和 [Minimize] [Maximize] 按钮的可见状态)的固定值) 并检查它是否仍然是积极的。这可能无法为您提供完全准确的结果,但它可能是最简单的近似值。

到目前为止,这种方法似乎可以计算出相当准确的近似值:

/// <summary>
/// Calculates an approximation of the available caption width
/// Depends on OS and theme
/// </summary>
/// <returns>Width</returns>
private int CalcAvaliableCaptionWidth()
{
    return
    // Form width
    Width
    // Icon
    - (Icon == null ? 0 : Icon.Width)
    // Minimize button (26 on Win8)
    - (MinimizeBox ? SystemInformation.CaptionButtonSize.Width : 0)
    // Maximize button (26 on Win8)
    - (MaximizeBox ? SystemInformation.CaptionButtonSize.Width : 0)
    // Close button (45 on Win8)
    - SystemInformation.CaptionButtonSize.Width;
}

你可以试试我的小验证 WinForm 应用程序

源代码: https://gist.github.com/CodeZombieCH/b9def0b0d9c41a98593a

感谢@Plutonix 对SystemInformation.CaptionButtonSize 的提示。

【讨论】:

  • 我相信你知道这个答案是不完整的。您如何确定生成的 textSize 是否适合没有标准按钮和上下文菜单图标的表单标题区域?
  • 使用System.Windows.Forms.SystemInformation.CaptionButtonSize 获取标准标题栏按钮的大小。它们的数量将取决于其他表单道具(MinimizeBox、ControlBox 等)。
  • CodeZombie 和 @Plutonix,谢谢,效果很好!
猜你喜欢
  • 1970-01-01
  • 2011-02-12
  • 2018-09-06
  • 2010-09-12
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
相关资源
最近更新 更多