public static void SetCharFormatFont(this RichTextBox richTextBox, bool selectionOnly, Gdi32Font font) { IntPtr handle = richTextBox.Handle; if (handle == IntPtr.Zero) { throw new InvalidOperationException(); } int dwMask = -1476394993; int num = 0; if (font.Bold != BooleanConsts.FALSE) { num |= CFM_BOLD; } if (font.Italic != BooleanConsts.FALSE) { num |= CFM_ITALIC; } if (font.Underline != BooleanConsts.FALSE) { num |= CFM_UNDERLINE; } if (font.Strikeout != BooleanConsts.FALSE) { num |= CFM_STRIKEOUT; } byte[] bytes; if (Marshal.SystemDefaultCharSize == 1) { throw new PlatformNotSupportedException(); } bytes = Encoding.Unicode.GetBytes(font.Logfont.lfFaceName); CHARFORMATW cHARFORMATW = new CHARFORMATW(); for (int j = 0; j < bytes.Length; j++) { cHARFORMATW.szFaceName[j] = bytes[j]; } cHARFORMATW.dwMask = dwMask; cHARFORMATW.dwEffects = num; cHARFORMATW.yHeight = (int)(font.SizeInPoints * 20f); cHARFORMATW.bCharSet = font.Logfont.lfCharSet; cHARFORMATW.bPitchAndFamily = font.Logfont.lfPitchAndFamily; SendMessage(new HandleRef(richTextBox, handle), EM_SETCHARFORMAT, selectionOnly ? SCF_SELECTION : SCF_ALL, cHARFORMATW); }
public unsafe void CharFormat_FaceName() { CHARFORMATW charFormat = default; charFormat.FaceName = "TwoFace"; Assert.Equal("TwoFace", charFormat.FaceName.ToString()); // Set a smaller name to make sure it gets terminated properly. charFormat.FaceName = "Face"; Assert.Equal("Face", charFormat.FaceName.ToString()); // CHARFORMAT has space for 32 characters, we want to see it gets // cut to 31 to make room for the null. string bigString = new string('*', 32); charFormat.FaceName = bigString; Assert.True(charFormat.FaceName.SequenceEqual(bigString.AsSpan().Slice(1))); }
public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPStruct)][In][Out] CHARFORMATW lParam);