PictureBox MouseEnter/MouseLeave事件未触发

dba*_*ett 6 vb.net winforms

使用三个图片框创建一个新表单.此代码用于在鼠标进入图片框时绘制边框,并在其离开时将其删除.结果不一致.有时它会绘制/移除边框,有时则不会.这段代码并不复杂.使用VS 2012.

Private Sub PictureBox_MouseEnter(sender As Object, e As EventArgs) _
    Handles PictureBox1.MouseEnter, PictureBox2.MouseEnter, PictureBox3.MouseEnter
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    pb.BorderStyle = BorderStyle.FixedSingle
    ' Debug.WriteLine("E " & pb.Name)
End Sub

Private Sub PictureBox_MouseLeave(sender As Object, e As EventArgs) _
    Handles PictureBox1.MouseLeave, PictureBox2.MouseLeave, PictureBox3.MouseLeave

    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    pb.BorderStyle = BorderStyle.None
    ' Debug.WriteLine("X " & pb.Name)
End Sub
Run Code Online (Sandbox Code Playgroud)

Kal*_*Nag 1

我也可以重现这个问题。因此,扩展上面关于“绘制其他内容”而不是使用 Picturebox 的属性的评论,让我建议这种快速而肮脏的方法:

  • 使用 RectangleShape 对象,该对象由VisualBasic Powerpack 3.0插件提供。只需以与 PictureBox 相同的形式放置其中之一,并使其不可见(visible = false)。

  • 代码也很简单:

    Public Class Form1
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.RectangleShape1.Location = New Point(Me.PictureBox1.Left - 1, Me.PictureBox1.Top - 1)
            Me.RectangleShape1.Size = New Size(Me.PictureBox1.Width + 1, Me.PictureBox1.Height + 1)
        End Sub
    
        Private Sub PictureBox1_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureBox1.MouseEnter
            Me.RectangleShape1.Visible = True
        End Sub
        Private Sub PictureBox1_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureBox1.MouseLeave
            Me.RectangleShape1.Visible = False
        End Sub
    End Class
    
    Run Code Online (Sandbox Code Playgroud)