Como faço para definir o RichTextBox.SelectionFont FontFamily sem alterar o estilo?
-
06-07-2019 - |
Pergunta
Um dos controles no meu aplicativo limita um usuário para ser capaz de alterar apenas o estilo da fonte (B, I, L) e cor do texto. Eu criei um controle personalizado que herda do RichTextBox para esta finalidade. Eu sou capaz de interceptar CTRL-V, e definir a fonte do texto colado para SystemFonts.DefaultFont
. O problema que estou enfrentando atualmente é se o texto colado contém, por exemplo, metade negrito metade estilo regular -. O negrito é perdido
i. "Foo Bar " só vai colar como "Foo Bar".
A minha única idéia atualmente é atravessar o texto caractere por caractere ( muito lento), e fazer algo como:
public class MyRichTextBox : RichTextBox
{
private RichTextBox hiddenBuffer = new RichTextBox();
/// <summary>
/// This paste will strip the font size, family and alignment from the text being pasted.
/// </summary>
public void PasteUnformatted()
{
this.hiddenBuffer.Clear();
this.hiddenBuffer.Paste();
for (int x = 0; x < this.hiddenBuffer.TextLength; x++)
{
// select the next character
this.hiddenBuffer.Select(x, 1);
// Set the font family and size to default
this.hiddenBuffer.SelectionFont = new Font(SystemFonts.DefaultFont.FontFamily, SystemFonts.DefaultFont.Size, this.hiddenBuffer.SelectionFont.Style);
}
// Reset the alignment
this.hiddenBuffer.SelectionAlignment = HorizontalAlignment.Left;
base.SelectedRtf = this.hiddenBuffer.SelectedRtf;
this.hiddenBuffer.Clear();
}
}
Alguém pode pensar em um produto de limpeza (e mais rápido) solução?
Solução
'nobugz' over nos fóruns do MSDN respondeu a esta para mim (eu precisava de uma resposta rapidamente, por isso depois de quase um dia de tumbleweed do SO, eu tive que procurar em outro lugar - não me julgue!):
using System.Runtime.InteropServices;
...
public static bool SetRtbFace(RichTextBox rtb, Font font, bool selectionOnly) {
CHARFORMATW fmt = new CHARFORMATW();
fmt.cbSize = Marshal.SizeOf(fmt);
fmt.szFaceName = font.FontFamily.Name;
fmt.dwMask = 0x20000000; // CFM_FACE
return IntPtr.Zero != SendMessage(rtb.Handle, 0x444, (IntPtr)(selectionOnly ? 1 : 4), fmt);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private class CHARFORMATW {
public int cbSize;
public int dwMask;
public int dwEffects;
public int yHeight;
public int yOffset;
public int crTextColor;
public byte bCharSet;
public byte bPitchAndFamily;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x40)]
public string szFaceName;
}
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, CHARFORMATW lParam);
Outras dicas
Para aqueles que querem uma resposta Delphi, um extrato para dar-lhe a idéia básica:
using RichEdit; //reqd. for the constants and types
var
chformat : TCharFormat2;
fontname : string;
begin
FillChar(chformat,sizeof(chformat),0);
chformat.cbSize := sizeof(chformat);
//only modify the szFaceName field, height etc. left alone
chformat.dwMask := CFM_FACE;
//get the fontname set by the user
fontname := AdvFontSelector1.Text;
strpcopy(chformat.szFaceName,fontname);
RichEdit1.Perform(EM_SETCHARFORMAT, SCF_SELECTION, lparam(@chformat));
end;