Adding strings to a RichTextBox in C#
I currently have a function that will set a value to a RichTextBox, although how could you "add" a value or a new line to it, rather than overwriting existing data in 开发者_Go百科the RichTextBox?
richTextBox2.Text = DateTime.Today + " Hello";
richTextBox2.AppendText(Environment.NewLine + DateTime.Today + " Hello");
richTextBox2.AppendText(String.Format("{0} the date is {1}{2}", "Hello", DateTime.Today, Environment.NewLine));
Please don't use +
richTextBox2.Document.Blocks.Clear();
richTextBox2.Document.Blocks.Add(new Paragraph(new Run("string")));
I wrote this as a simple log-to-screen kinda thing to inform user of stuff going on in the background or to acknowledge various actions.
Add a RichTextBox on the form, here I call it "rtbLog"
Then call the below and add your message and any optional formatting you want. So for example:
DoWriteToLog("Hey, welcome!", true, Color.Green)
public void DoWriteToLog(string strLogMessage, bool blnHighlighted = false, Color myFontColor = default(Color), bool blnNewLine = true)
{
string dtStamp = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
if (blnNewLine)
strLogMessage = dtStamp + strLogMessage + Environment.NewLine;
if (blnHighlighted)
{
rtbLog.SelectionColor = myFontColor; // Optional font color passed to method
if (strLogMessage.ToLower().Contains("help")) // IF there is 'help' in the message, highlight it blue
rtbLog.SelectionBackColor = Color.LightBlue;
rtbLog.SelectionFont = new Font("Cambria", 10F, FontStyle.Bold, GraphicsUnit.Point);
rtbLog.AppendText(strLogMessage);
}
else
rtbLog.AppendText(strLogMessage);
rtbLog.ScrollToCaret();
}
The above DoWriteToLog statement will write "Hey, welcome!" to the RichTextBox in bold Green font. It adds a timestamp to each line entered as well, but you can avoid that by turning off blnNewLine. Of course it's specific to my use, but you can modify it to suit yours.
I also have a help 'detector' in there so if I am putting a help message on the screen it highlights it a specific color, you can comment/delete those two lines as needed.
Note the only required parameter, of course, is the message. This way, since I use this a lot, I don't have to add all the parameters every time thus, saving lots of typing :-)
richTextBox2.Text = "Something " + richTextBox2.Text + " and something"
精彩评论