Remove 或 Delete 画在 PictureBox 上的 Rectangle

Remove Or Delete the Rectangle drawn on the PictureBox

我目前正在解决一个错误,该错误会删除 PictureBox 上创建的矩形。问题是,当我单击 PictureBox 上的一个项目并调整 windows 表单的大小时,矩形不会随着所选项目继续移动。这是创建矩形的代码:

Private Sub paintRectangle(pictBox As System.Windows.Forms.PictureBox, pic As Image)
    If pic Is Nothing Then Exit Sub

    pictBox.Image = pic

    If m_rect_x = -1 And m_rect_y = -1 Then
        Return
    End If

    Dim graphic As System.Drawing.Graphics
    Dim redselpen As System.Drawing.Pen
    Dim yNegative As Integer = 3    

    redselpen = New System.Drawing.Pen(Color.Blue)

    redselpen.DashStyle = Drawing2D.DashStyle.DashDot
    If pictBox.Image IsNot Nothing Then
        graphic = System.Drawing.Graphics.FromImage(pictBox.Image)
        graphic.DrawRectangle(redselpen, m_rect_x, m_rect_y - yNegative, SystemConfig.iRectWidth, SystemConfig.iRectHeight + 2)
        pictBox.Image = pictBox.Image
    End If
End Sub

调整窗体大小后,我想删除在 PictureBox 上创建的矩形。

我试过这个解决方案,但矩形仍然在 PictureBox 中。

How to remove all the drawn rectangles on the picture box? (Not on the image)

但是不行,矩形还在图片框里。

这里有一个简单的例子,展示了 PictureBox 的 Paint() 事件被用来绘制一个可以移动和旋转的矩形 on/off:

Public Class Form1

    Private yNegative As Integer = 3
    Private pt As New Nullable(Of Point)
    Private drawRectangle As Boolean = False

    Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint
        If drawRectangle AndAlso pt.HasValue Then
            Using redselpen As New System.Drawing.Pen(Color.Blue)
                redselpen.DashStyle = Drawing2D.DashStyle.DashDot
                e.Graphics.DrawRectangle(redselpen, pt.Value.X, pt.Value.Y - yNegative, SystemConfig.iRectWidth, SystemConfig.iRectHeight + 2)
            End Using
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        pt = New Point(25, 25)
        drawRectangle = True
        PictureBox1.Invalidate()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        drawRectangle = Not drawRectangle ' toggle the rectangle on/off
        PictureBox1.Invalidate()
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        pt = New Point(150, 25)
        drawRectangle = True
        PictureBox1.Invalidate()
    End Sub

End Class