vb继承自TextBox的.NET自定义控件不会触发Paint事件

时间:2010-08-25 09:01:33

标签: vb.net custom-controls

我需要一个总是禁用的多行TextBox,但它不应该用灰色绘制自己,但我想让设计师选择颜色。

我之前对一个始终为黑色的标签(没有多行)有同样的要求,所以我从Label继承了:

Imports System.ComponentModel

   Public Class LabelDisabled
        Inherits Label

        Sub New()
            InitializeComponent()
            Enabled = False
        End Sub

        Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
            ' always draw it black
            e.Graphics.DrawString(Me.Text, Me.Font, Brushes.Black, 0, 0)
        End Sub

    End Class

工作正常。现在我想要相同的东西,但有多行标签,所以我选择继承TextBox:

Imports System.ComponentModel

Public Class CustomControl1
    Inherits TextBox

    Sub New()

        InitializeComponent()
        'Paint never fires anyway
        'Enabled = False
    End Sub


    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        Dim brush As New SolidBrush(Me.ForeColor)
        e.Graphics.DrawString(Me.Text, Me.Font, brush, 0, 0)
    End Sub

End Class

现在,Paint事件永远不会在CustomControl1中继承 - TextBox继承 - 控制。

为什么我不能获得Paint事件?

另外,如果我想让Enabled属性不可见且用户不可设置,我会这样做:

<Browsable(False),
DefaultValue(False)>
Public Overloads Property Enabled As Boolean
    Get
        Return False
    End Get
    Set(ByVal value As Boolean)
    End Set
End Property

但是这样,我既不能设置“真正的”Enabled属性,也就是支持字段。

2 个答案:

答案 0 :(得分:4)

我找到了解决方案。即使对于子类,看起来像TextBox也会禁用Paint事件。但是你可以强制WM_PAINT位调用SetStyle:

Public Class DisabledTextBox
    Inherits TextBox

    Public Sub New()
        InitializeComponent()

        Enabled = False
        SetStyle(ControlStyles.Selectable, False)
        SetStyle(ControlStyles.UserPaint, True)

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
        Dim brush As New SolidBrush(Me.ForeColor)
        e.Graphics.DrawString(Me.Text, Me.Font, brush, 0, 0)
    End Sub

End Class

按预期完美运作:)

答案 1 :(得分:0)

这是你的答案:

Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
    MyBase.OnPaint(e)
    e.Graphics.FillRectangle(Brushes.LightGray, Me.DisplayRectangle)
    Dim sf As New StringFormat
    sf.FormatFlags = StringFormatFlags.NoWrap
    sf.HotkeyPrefix = Drawing.Text.HotkeyPrefix.Show 'if Mnemonic property is set to true
    sf.HotkeyPrefix = Drawing.Text.HotkeyPrefix.Hide 'or none if Mnemonic property is set to false
    sf.LineAlignment = StringAlignment.Center 'horizontal alignment
    sf.Alignment = StringAlignment.Center ' vertical ...
    Dim rect As Rectangle = Me.DisplayRectangle ' this is your text bounds for setting your text alignement using StringFormat(sf)
    e.Graphics.DrawString("Something", Me.Font, Brushes.DarkOliveGreen, rect, sf)
End Sub