0

I am overriding the paint event as I need to give a text box an extra property. In this case the extra property is a border colour for a text box. When the User Control which contains the text boxes appears it does not fire the OnPaint event. I've no idea why this is happening.

My code is as follows

CustomTaskBox class

Public Class CustomTextBox
    Inherits TextBox

    <Browsable(True)>
    <Category("Extended Properties")>
    <Description("Set TextBox border Color")>
    Public Sub New()

        Multiline = False
        BorderStyle = BorderStyle.None

    End Sub


    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Dim buttonPen = New Pen(Color.Firebrick, 3)
        Dim buttonRect = New Rectangle(0, 0, Size.Width - 1, Size.Height - 1)
        e.Graphics.DrawRectangle(buttonPen, buttonRect)
    End Sub

End Class

Main Class

Dim _NewTextBox As New CustomTextBox
_NewTextBox.Name = textBoxName
_NewTextBox.Multiline = multiline
_NewTextBox.Text = textBoxText
_NewTextBox.Top = topForNextControl
_NewTextBox.Left = 17
_NewTextBox.Width = textBoxWidth * widthScaleFactor
_MainContent.Controls.Add(_NewTextBox)
Magnetron
  • 7,495
  • 1
  • 25
  • 41
Craig Gallagher
  • 1,613
  • 6
  • 23
  • 52
  • 1
    The TextBox control still harks back to the 1990s. It doesn't call a paint event. You would have to override the WndProc to find the message. Custom painting the TextBox control never ends well. Just stick it inside a panel to create a border. – LarsTech Jan 11 '18 at 16:51
  • @LarsTech Thanks for your comment. I can't believe that textbox doesn't call a paint event and it is that awkward to add a border colour to a textbox. Quite shocking really – Craig Gallagher Jan 11 '18 at 17:34
  • WPF lets you customize all that kind of stuff. WinForms has legacy issues that it deals with. See [Textbox custom onPaint](https://stackoverflow.com/q/17414693/719186) for someone else's attempt. – LarsTech Jan 11 '18 at 17:38
  • To have a TextBox raise the OnPaint event, you could use the SetStyle method: `Me.SetStyle(ControlStyles.UserPaint, True)`. But this is just a hack (you'll see when you try to set the Background color). It's much less complicated with a UserControl that contains a TextBox. However, take a look at [Change border color in TextBox](https://stackoverflow.com/questions/17466067/change-border-color-in-textbox-c-sharp/39420512#39420512). – Jimi Jan 11 '18 at 17:50

1 Answers1

0

If I recall correctly - you need to useInvalidate(); to notify that control needs to be repainted.