torstai 2. lokakuuta 2008

Textbox with custom border

People always ask how to create a TextBox with a custom border in C#. Unfortunately you can't achieve the goal by overriding the Paint() or PaintBackground() events. TextBox is one of those controls whose drawing is handled by Windows so for example Paint() event is never fired.

We can tweak around this problem by creating a custom control which holds a TextBox control inside it. The textbox's Borderstyle must be set to none. Now we can draw the border in custom controls Paint() event.

Remember! Textbox has to be placed like this:

Location: (1,1)
Size: (textBox.Width - 2, textBox.Height - 2)

Now you just have to draw a rectangle around the textbox area:

graphics.DrawRectangle(borderPen, new Rectangle(0, 0, this.Width - 1, this.Height - 1));

Ei kommentteja: