选择多个尺寸时,Richtextbox SelectionFont.Size

时间:2010-05-26 20:34:24

标签: c# .net vb.net controls

当WindowsForms RichTextbox中的选择使用两种或更多不同的字体大小时(例如,您在同一选择中选择字体大小为9的文本和字体大小为16的其他文本),SelectionFont.Size始终返回13.是否有任何字体检测两种不同尺寸的方法?

2 个答案:

答案 0 :(得分:0)

我不是100%肯定,但我认为这样做的唯一方法是循环检查并分别检查每个字符的字体大小。

答案 1 :(得分:0)

如果选择的范围包含具有相同字体的项目, 但是不同的大小,控件错误地报告选择包含大小为13的字体。我不确定这是否可以修复。也许在这种情况下总是13,也许不是,我不知道。

但我使用以下解决方案...
通过Methode中的反思发现

public class RichTextBox : TextBoxBase ...
  private Font GetCharFormatFont(bool selectionOnly)**

示例代码:
内容=> RichTextBox-Control

// var lSize = Content.SelectionSize;
var lSize = RichTextBoxHelper.GetSelectionSize(Content);

if (lSize.HasValue)
  ComboBoxFontSize.Text = Convert.ToString(lSize.Value);
else
  // Multible Sizes ...
  ComboBoxFontSize.Text = string.Empty;

Helper Methode(Class):

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace UnimatrixOne
{
  public class RichTextBoxHelper
  {
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [In, Out, MarshalAs(UnmanagedType.LPStruct)] CHARFORMATA lParam);

    private const long CFM_SIZE = 0x80000000;
    private const int EM_GETCHARFORMAT = 0x043A;
    private const int SCF_SELECTION = 0x01;

    /// <summary> 
    /// Contains information about character formatting in a rich edit control. 
    /// </summary> 
    /// <remarks><see cref="CHARFORMAT"/>works with all Rich Edit versions.</remarks> 
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public class CHARFORMATA
    {
      public int cbSize = Marshal.SizeOf(typeof(CHARFORMATA));
      public int dwMask;
      public int dwEffects;
      public int yHeight;
      public int yOffset;
      public int crTextColor;
      public byte bCharSet;
      public byte bPitchAndFamily;
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
      public byte[] szFaceName = new byte[32];
    }

    /// <summary> 
    /// Gets or sets the underline size off the current selection. 
    /// </summary>
    [Browsable(false),
    DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public static float? GetSelectionSize(RichTextBox control)
    {
      var lParam = new CHARFORMATA();
      lParam.cbSize = Marshal.SizeOf(lParam);

      // Get the underline style 
      SendMessage(new HandleRef(control, control.Handle), EM_GETCHARFORMAT, SCF_SELECTION, lParam);
      if ((lParam.dwMask & -CFM_SIZE) != 0)
      {
        float emSize = ((float)lParam.yHeight) / 20f;

        if ((emSize == 0f) && (lParam.yHeight > 0))
          emSize = 1f;

        return emSize;
      }
      else
        return null;
    }
  }
}