处理 VScrollbar Paint 事件

Handling VScrollbar Paint event

我一直在尝试为窗体上的控件处理 Paint 事件。但是,该事件从未得到处理,而且我不确定自己做错了什么。我创建了一个非常简单的 WinForms 项目来演示这一点(我包含了生成的设计器代码以表明那里没有其他东西):

Form1.vb

Public Class Form1
    Private Sub Form1_Load( sender As Object,  e As EventArgs) Handles MyBase.Load
        AddHandler VScrollBar1.Paint, AddressOf VScrollBar1_Paint
    End Sub

    Private Sub VScrollBar1_Paint (ByVal sender As Object, ByVal e As PaintEventArgs)
        Dim str As String = "test"
        System.Windows.Forms.MessageBox.Show(str)
    End Sub                              
End Class

Form1.Designer.vb

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.VScrollBar1 = New System.Windows.Forms.VScrollBar()
        Me.SuspendLayout
        '
        'VScrollBar1
        '
        Me.VScrollBar1.Location = New System.Drawing.Point(26, 56)
        Me.VScrollBar1.Name = "VScrollBar1"
        Me.VScrollBar1.Size = New System.Drawing.Size(17, 80)
        Me.VScrollBar1.TabIndex = 0
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6!, 13!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(284, 261)
        Me.Controls.Add(Me.VScrollBar1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(false)

    End Sub
        Friend WithEvents VScrollBar1 As System.Windows.Forms.VScrollBar

End Class

从未处理该事件,但正确绘制了控件。我错过了什么?

好吧,在这上面花了更多时间之后,我发现您需要做的就是调用 SetStyle() 方法,并将标志和值参数设置为 ControlStyles.userPaintTrue, 分别.

虽然这个方法不是 public,因此需要反射才能调用它:

Dim methodInfo As System.Reflection.MethodInfo = VScrollBar1.GetType().GetMethod("SetStyle", Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic)
methodInfo.Invoke(VScrollBar1, {ControlStyles.UserPaint, True})

我将上面的代码放入上面的 Form1_Load 方法中,就在 AddHandler 行上方,它似乎可以工作(我可以处理事件)。