Wednesday, March 11, 2009

CodeBox – A WPF chroma keying and simple formatting textbox

CodeProjectCodeBox

“A fast WPF textbox control with support for text coloring, highlighting, underlines, and strikethroughs.

CodeBox

This article presents an enhanced text box control that is designed to facilitate text coloring, highlighting, underlining, and striking. As it is derived from the TextBox control, rather than the RichTextBox, it is quite speedy.

Background

I was in the process of upgrading a Regular Expression generating tool of mine. For the nth time, I was considering moving it from WinForms to WPF. My problem was the painful slowness of the RichTextBox control. I had tried numerous times to somehow get performance that compared to the WinForms RichTextBox, but failed. This time, I tried something different. For the heck of it, I overrode the OnRender method, and wrote a little text to the TextBox. I was surprised to find that both the textbox’s text and my additional text were visible, as I expected only my overridden text to appear. It took a few moments to progress from Oh that’s odd to Wow, my problem is solved, as I could now do the following.

  • Recreate the same text as was in the textbox, but colorized and otherwise decorated
  • Since both sets of text are visible, I can make sure that they line up exactly
  • The original text's brush can be set to something transparent so it will not cover up the decorated text
  • Selecting and editing will be handled by the underling text box functionality

I figured that this couldn’t possibly be slower than the RichTextBox, so I gave it a try. It exceeded my expectations, so here it is.

Using the Code

This control can be used like a regular textbox with the following caveats. The background and foreground brushes should both be set to something transparent. This is done in the constructor so all one needs to do is not set them. In order to set the default text color, use the BaseForeground property. In order to set the background color, just wrap it in a border. Hopefully, I will be able to remove this nonstandard behavior soon. Text coloring rules are set through the Decorations property.

…”

I’ve been thinking about including chroma keying/text coloring in some of my apps (including color code SQL ;) so I keyed in on this…

No comments: