I have winform with a TextBox and I want to draw some GDI graphics on top of it. The text box does not have a Paint()
event to hook to, so I assume it all has t
It can be relatively tricky to owner-draw the TextBox
control because it's simply a wrapper around the native Win32 TextBox
control.
The easiest way to capture the WM_PAINT
messages that you need to handle for your custom painting routines to work is by inheriting from the NativeWindow class.
Here is an excellent step-by-step article that shows how to do this in the context of displaying the red wavy underlines: Owner-drawing a Windows.Forms TextBox (original link dead; replaced by archived version)
The System.Windows.Forms.TextBox class does have a Paint event: http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.paint.aspx. According to the MSDN it is not intended to be used in your code, but you might not have any other option if you do not want to create your own control using inheritance.
If you want to draw inside the TextBox you should use its Paint and a Graphics object created from its handle. If you draw using the Form's Paint even, when the TextBox receives its own Paint event it will override the previous draw since the TextBox is on top of the Form.
If you are not using the Paint event of the TextBox, you can still get its Graphics object using the CreateGraphics method. However, you will have to be careful to do your drawing after the TextBox's Paint event, otherwise it might get overridden.
In the end you might need to create your own control inheriting from TextBox. Inheritance is a powerful method of overriding default behavior in Windows Forms programming.
Please let me know if you need additional help.