Search code examples
vb.netpictureboxrectanglesdrawrectangle

Why my rectangle is not drawing in a picturebox? (Dragging)


So, I tried to do draw a rectangle by dragging my mouse in a form, and I was successful, but when I try to do the same way in a picturebox no rectangle is created.

Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove

        If fGMouseIsDown And Not PictureBox1.Image Is Nothing Then

            rect.Width = e.X - rect.X
            rect.Height = e.Y - rect.Y
             Invalidate()


        End If
    End Sub

Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown

        fGMouseIsDown = True
        rect.Location = e.Location
        rect.Width = 0
        rect.Height = 0
        Invalidate()
    End Sub 

Private Sub PictureBox1_Paint(sender As Object, e As PaintEventArgs) Handles PictureBox1.Paint

        e.Graphics.DrawRectangle(Pens.Blue, rect)

End Sub

Solution

  • Per @HansPassant: The Invalidate() call in your PictureBox1_MouseDown() method invalidates the form, when you instead want to invalidate the picture box.

    That call should instead be:

    PictureBox1.Invalidate()
    

    Additionally, ensure you drag the right way; this will only work when you go from top-left to bottom-right.