2011-01-06 16 views
15

Cuando se utiliza el control Microsoft RichTextBox es posible añadir nuevas líneas de este tipo ...cómo anexar line en RTF utilizando el control RichTextBox

richtextbox.AppendText(System.Environment.NewLine); // appends \r\n 

Sin embargo, si ahora ve la RTF generado la \ r \ n los caracteres se convierten en \ par no \ línea

¿Cómo inserto un código de control \ line en el RTF generado?

Lo does't de trabajo:

reemplazo de emergencia

Hacks como la inserción de una ficha al final de la cadena y luego reemplazarla después del hecho, por lo menos así:

string text = "my text"; 
text = text.Replace("||" "|"); // replace any '|' chars with a double '||' so they aren't confused in the output. 
text = text.Replace("\r\n", "_|0|_"); // replace \r\n 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 | 

Esto casi funciona, se rompe si tiene que apoyar el texto de derecha a izquierda, ya que la secuencia de control de derecha a izquierda siempre termina en el medio del marcador de posición

envío de mensajes clave

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); 
} 

Esto también termina siendo convertidos a un \ par

¿Hay una manera de publicar un contactado directamente al control Msftedit para insertar un carácter de control?

Estoy totalmente perplejo, ¿alguna idea, chicos? ¡Gracias por tu ayuda!

Respuesta

17

Adición de un Unicode "línea de separación" (U + 2028) Cómo funciona tanto como mis pruebas mostró:

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); 
} 

Cuando ejecuto el programa, me sale:

Hello, World! 
Hello, World! 
{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fnil\fcharset0 Courier New;}} 
{\colortbl ;\red255\green255\blue255;} 
\viewkind4\uc1\pard\cf1\f0\fs17 Hello, World!\line Hello, World!\line\par 
} 

Se añadía \line en lugar de \par.

+0

Una nota, sin embargo, la emulación RichTextBox de mono está bastante rota y, entre otras incompatibilidades, no comprende el separador de línea. Aparece como un carácter de cuadro en el texto. –

+0

Esto funcionó como un encanto para mí, me permitió eliminar el horrible truco que teníamos en su lugar. ¡Nuestros clientes te lo agradecerán! –

6

Dado que desea utilizar un código RTF diferente, creo que puede que necesite olvidarse del método simplista AppendText() y manipular directamente la propiedad .Rtf de su RichTextBox. Aquí está una muestra (prueba) para demostrar:

RichTextBox rtb = new RichTextBox(); 
//this just gets the textbox to populate its Rtf property... may not be necessary in typical usage 
rtb.AppendText("blah"); 
rtb.Clear(); 

string rtf = rtb.Rtf; 

//exclude the final } and anything after it so we can use Append instead of Insert 
StringBuilder richText = new StringBuilder(rtf, 0, rtf.LastIndexOf('}'), rtf.Length /* this capacity should be selected for the specific application */); 

for (int i = 0; i < 5; i++) 
{ 
    string lineText = "example text" + i; 
    richText.Append(lineText); 
    //add a \line and CRLF to separate this line of text from the next one 
    richText.AppendLine(@"\line"); 
} 

//Add back the final } and newline 
richText.AppendLine("}"); 


System.Diagnostics.Debug.WriteLine("Original RTF data:"); 
System.Diagnostics.Debug.WriteLine(rtf); 

System.Diagnostics.Debug.WriteLine("New Data:"); 
System.Diagnostics.Debug.WriteLine(richText.ToString()); 


//Write the RTF data back into the RichTextBox. 
//WARNING - .NET will reformat the data to its liking at this point, removing 
//any unused colors from the color table and simplifying/standardizing the RTF. 
rtb.Rtf = richText.ToString(); 

//Print out the resulting Rtf data after .NET (potentially) reformats it 
System.Diagnostics.Debug.WriteLine("Resulting Data:"); 
System.Diagnostics.Debug.WriteLine(rtb.Rtf); 

Salida:

Los datos originales RTF:

 
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}} 
\viewkind4\uc1\pard\f0\fs17\par 
} 

Nuevos datos RTF:

 
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}} 
\viewkind4\uc1\pard\f0\fs17\par 
example text0\line 
example text1\line 
example text2\line 
example text3\line 
example text4\line 
} 

resultante RTF datos:

 
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}} 
\viewkind4\uc1\pard\f0\fs17\par 
example text0\line example text1\line example text2\line example text3\line example text4\par 
} 
5

si está utilizando párrafos escribir en RichTextbox puede utilizar el LineBreak() mismo código se muestra a continuación

Paragraph myParagraph = new Paragraph(); 
FlowDocument myFlowDocument = new FlowDocument(); 

// Add some Bold text to the paragraph 
myParagraph.Inlines.Add(new Bold(new Run(@"Test Description:"))); 
myParagraph.Inlines.Add(new LineBreak()); // to add a new line use LineBreak() 
myParagraph.Inlines.Add(new Run("my text")); 
myFlowDocument.Blocks.Add(myParagraph); 
myrichtextboxcontrolid.Document = myFlowDocument; 

Espero que esto ayude!

+0

esto funciona para mi solución - gracias – lukaszk

+0

es la solución perfecta – Ambyte