Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
762 views
in Technique[技术] by (71.8m points)

c# - How to append line into RTF using RichTextBox control

When using the Microsoft RichTextBox control it is possible to add new lines like this...

richtextbox.AppendText(System.Environment.NewLine); // appends 

However, if you now view the generated rtf the characters are converted to par not line

How do I insert a line control code into the generated RTF?

What does't work:

Token Replacement

Hacks like inserting a token at the end of the string and then replacing it after the fact, so something like this:

string text = "my text";
text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output.
text = text.Replace("
", "_|0|_"); // replace 
 with a placeholder of |0|

richtextbox.AppendText(text);

string rtf = richtextbox.Rtf;
rtf.Replace("_|0|_", "\line"); // replace placeholder with line
rtf.Replace("||", "|"); // set back any || chars to |

This almost worked, it breaks down if you have to support right to left text as the right to left control sequence always ends up in the middle of the placeholder.

Sending Key Messages

public void AppendNewLine()
{
    Keys[] keys = new Keys[] {Keys.Shift, Keys.Return};
    SendKeys(keys);
}

private void SendKeys(Keys[] keys)
{
    foreach(Keys key in keys)
    {
        SendKeyDown(key);
    }
}

private void SendKeyDown(Keys key)
{
    user32.SendMessage(this.Handle, Messages.WM_KEYDOWN, (int)key, 0);
}

private void SendKeyUp(Keys key)
{
    user32.SendMessage(this.Handle, Messages.WM_KEYUP, (int)key, 0);
}

This also ends up being converted to a par

Is there a way to post a messaged directly to the msftedit control to insert a control character?

I am totally stumped, any ideas guys? Thanks for your help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Adding a Unicode "Line Separator" (U+2028) does work as far as my testing showed:

private void Form_Load(object sender, EventArgs e)
{
    richText.AppendText("Hello, World!u2028");
    richText.AppendText("Hello, World!u2028");
    string rtf = richText.Rtf;
    richText.AppendText(rtf);
}

When I run the program, I get:

Hello, World!
Hello, World!
{
tf1ansiansicpg1252deff0deflang1031{fonttbl{f0fnilfcharset0 Courier New;}}
{colortbl ;
ed255green255lue255;}
viewkind4uc1pardcf1f0fs17 Hello, World!line Hello, World!linepar
}

It did add line instead of par.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...