스타일을 변경하지 않고 RichTextBox.SelectionFont FontFamily를 어떻게 설정합니까?
-
06-07-2019 - |
문제
내 응용 프로그램의 컨트롤 중 하나는 사용자가 글꼴 스타일 (B, I, U)과 텍스트의 색상 만 변경할 수 있도록 제한합니다. 이 목적을 위해 RichTextBox에서 상속되는 사용자 정의 컨트롤을 만들었습니다. Ctrl-V를 가로 채고 붙여 넣은 텍스트의 글꼴을 다음으로 설정할 수 있습니다. SystemFonts.DefaultFont
. 내가 현재 직면하고있는 문제는 붙여 넣은 텍스트에 예를 들어 반 굵은 반 정규 스타일과 같은 대담한 사람이 포함 된 경우입니다.
즉 "foo 술집""foo bar "로 붙여 넣을 것입니다.
내 유일한 아이디어는 현재 문자 별 텍스트 문자를 거치는 것입니다.매우 느리게), 다음과 같은 일을하십시오.
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();
}
}
누구든지 더 깨끗하고 더 빠른 솔루션을 생각할 수 있습니까?
해결책
MSDN 포럼의 'Nobugz'는 저를 위해 이것에 대답했습니다 (나는 빨리 답변이 필요했기 때문에 거의 하루의 Tumbleweed에서 다른 곳을 봐야했습니다 - 나를 판단하지 마십시오!) : :
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);
다른 팁
델파이 대답을 원하는 사람들을 위해, 당신에게 기본 아이디어를 제공하는 추출물 :
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;
제휴하지 않습니다 StackOverflow