Jan 8, 2008

5 minutes C# code to help you blog source ...

As I was unabled to find a reliable editor to convert my code samples to html, I decided to write one. You need two richTextBox components, named richTextBox1 and richTextBox2 and a Button, named button1.

Here is the code you need to put into the button1 click event handler:
       private void button1_Click(object sender, EventArgs e)
       {
            
string oldColor = "-";
            
string newColor = string.Empty;

            
StringBuilder strHtml = new StringBuilder();

            
for (int i = 0; i < this.richTextBox1.Text.Length; i++)
            {
                richTextBox1.Select(i, 1);
               
newColor = System.Drawing.ColorTranslator.ToHtml(richTextBox1.SelectionColor);
               
if ((newColor != oldColor) && (newColor != string.Empty))
                {
                  
if (!oldColor.Equals("-"))
                   {
                        strHtml.Append(
"");
                   }
                   strHtml.Append(
" + newColor + ";\">");
                   oldColor = newColor;
                }
                strHtml.Append(richTextBox1.SelectedText.Replace(
"<", "<").Replace(">", ">"));
               
Application.DoEvents();
            }
            strHtml.Append(
""
);
            
StringBuilder sbNew = new StringBuilder();
            sbNew.Append(strHtml.ToString().Replace(
"   ", "   "));
            richTextBox2.AppendText(sbNew.ToString());
       }


PLEASE NOTE: this code was written in 5 or 10 minutes, it doesn't pretend to be either clean or readable, it simply works. If you want - you can take it, optimize it, use it or whatever, just have in mind it wasn't written carefully ;).

No comments: