Torna al Thread
' True while we are drawing the new line.
Private m_Drawing As Boolean
' Buffer for erasing rubberband lines.
Private m_BufferBitmap As Bitmap
Private m_BufferGraphics As Graphics
' The mouse position.
Private m_X1 As Integer
Private m_Y1 As Integer
Private m_X2 As Integer
Private m_Y2 As Integer
' Start drawing a rubberband line.
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e _
As System.Windows.Forms.MouseEventArgs) Handles _
PictureBox1.MouseDown
' Do nothing if this isn't the left mouse button.
If e.Button <> MouseButtons.Left Then Exit Sub
m_Drawing = True
' Save a snapshot of the form.
SaveSnapshot()
' Save the current mouse position.
m_X1 = e.X
m_X2 = e.X
m_Y1 = e.Y
m_Y2 = e.Y
End Sub
Private Sub SaveSnapshot()
Dim new_bitmap As Bitmap
' Make a new bitmap that fits the form.
new_bitmap = New Bitmap(PictureBox1.Size.Width, PictureBox1.Size.Height, PictureBox1.CreateGraphics())
m_BufferGraphics = Graphics.FromImage(new_bitmap)
' Clear the new bitmap.
m_BufferGraphics.Clear(PictureBox1.BackColor)
' Copy the existing bitmap's contents into
' the new bitmap.
If Not (m_BufferBitmap Is Nothing) Then
m_BufferGraphics.DrawImage(PictureBox1.Image, 0, 0)
End If
' Save the new bitmap and graphics objects.
m_BufferBitmap = new_bitmap
End Sub
' Continue drawing the rubberband line.
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e _
As System.Windows.Forms.MouseEventArgs) Handles _
PictureBox1.MouseMove
PictureBox1.Cursor = Cursors.Cross
' Do nothing if we're not drawing.
If Not m_Drawing Then Exit Sub
' Save the new point.
m_X2 = e.X
m_Y2 = e.Y
' Erase the previous line.
DrawPicBox(PictureBox1.CreateGraphics())
' Draw the new line directly on the form.
PictureBox1.CreateGraphics().DrawLine(Pens.Gray, m_X1, m_Y1, m_X2, m_Y2)
End Sub
' Redraw the saved buffer.
Private Sub DrawPicBox(ByVal gr As Graphics)
If Not (m_BufferBitmap Is Nothing) Then _
gr.DrawImage(m_BufferBitmap, 0, 0)
End Sub
' Finish drawing the new line.
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e _
As System.Windows.Forms.MouseEventArgs) Handles _
PictureBox1.MouseUp
' Do nothing if we're not drawing.
If Not m_Drawing Then Exit Sub
m_Drawing = False
' Save the new point.
m_X2 = e.X
m_Y2 = e.Y
' Draw the new line permanently on the buffer.
m_BufferGraphics.DrawLine( _
Pens.Red, m_X1, m_Y1, m_X2, m_Y2)
' Redraw to show the new line.
DrawPicBox(PictureBox1.CreateGraphics())
'TextBox2.Text = "X1 è: " & m_X1 & ", Y1 è: " & m_Y1
'TextBox3.Text = "X2 è: " & m_X2 & ", Y2 è: " & m_Y2
TextBox1.Text = GetDistance(m_X1, m_X2, m_Y1, m_Y2)
End Sub
' Redraw the form.
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
DrawPicBox(e.Graphics)
End Sub