This article describes how SharpSpell is able to modify existing TextBox controls to display wavy red underlines below misspelled words.
Here’s an image to demonstrate what I mean:
(This image is borrowed from SharpSpell, but you get the point)
Overview
The .NET framework provides means to subclass native Win32 windows and controls by inheriting from the NativeWindow class.
This is exactly what we need to do, and here is the basic outline of our inherited class:
Now we need to write the custom paint routine. In order to draw underlines underneath words, we need to know where these words are in the first place. We can get these values using Win32 API functions.
I will not go into detail with these API functions because the code is pretty long and doesn’t make the object of this article. You can download the support class here: Native Win32 Methods for measuring text inside a TextBox (nativemethods.zip)
The custom paint method
This is the CustomPaint() method:
We use the DrawWave() method to draw a wavy line (zig-zag) from one point to another – you can customize it to your needs:
Now to use this class, you just need to instantiate it by passing a TextBox control to the constructor. Make sure you keep a reference to it at the module level so it doesn’t get eaten by the Garbage Collector.
CustomPaintTextBox customUnderlines = new CustomPaintTextBox(textBox1);
I haven’t really tested this stripped out version of the class, but it should work. Most of it is taken directly from the SharpSpell source code.
I hope this article helps you understand how to owner draw native Win32 controls using the .NET framework. If you have any questions please leave a comment.
[tags]Windows.Forms, C#, User Interface, .NET Framework, Win32[/tags]