Option Strict On
Imports System.Drawing.Drawing2D
Public Class Form1
Friend WithEvents MainFrame As PictureBox
Friend WithEvents TextBox1 As TextBox
'Class level variables
Dim _blnMouseMove As Boolean = False
Dim Start As Point
Dim [End] As Point
Dim lstPaths As New List(Of GraphicsPath)
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.StartPosition = FormStartPosition.CenterScreen
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'set Form size
Me.Size = New Size(760, 500)
'Create a picturebox
MainFrame = New PictureBox
MainFrame.Location = New Point(16, 16)
MainFrame.Size = New Size(600, 400)
MainFrame.BackColor = Color.LightGray
'create a textbox
TextBox1 = New TextBox
TextBox1.Location = New Point(MainFrame.Right + 32, MainFrame.Top)
TextBox1.Size = New Size(Me.Width - 32 - TextBox1.Left, 32)
'add our created controls to form
Me.Controls.Add(MainFrame)
Me.Controls.Add(TextBox1)
End Sub
Private Sub MainFrame_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MainFrame.MouseDown
'remember we have a mouse button down
_blnMouseMove = True
Me.Start = New Point(MainFrame.Width \ 2, MainFrame.Height)
Me.End = e.Location
End Sub
Private Sub MainFrame_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MainFrame.MouseMove
'only draw line if mousebutton is down
If _blnMouseMove Then
Me.End = e.Location
'invalidates whole picturebox
'not the most eddicient way
MainFrame.Invalidate()
'live update of line angle
CalculateAngle(Me.Start, Me.End)
End If
End Sub
Private Sub MainFrame_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MainFrame.MouseUp
'forget we pressed down the mouse button
_blnMouseMove = False
'store the line we just drew
Dim p As New GraphicsPath
p.AddLine(Me.Start, Me.End)
lstPaths.Add(p)
CalculateAngle(Me.Start, Me.End)
End Sub
Private Sub MainFrame_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MainFrame.Paint
'only draw 'dragged' line if mouse button is pressed
If _blnMouseMove Then
e.Graphics.DrawLine(Pens.Black, Me.Start, Me.End)
End If
'draw centre line
e.Graphics.DrawLine(Pens.MediumPurple, MainFrame.Width \ 2, 0, MainFrame.Width \ 2, MainFrame.Height)
'draw stored lines
For Each gp As GraphicsPath In lstPaths
e.Graphics.DrawPath(Pens.Blue, gp)
Next
End Sub
Private Sub CalculateAngle(ByVal ptStart As Point, ByVal ptEnd As Point)
Dim op As Integer
Dim adj As Integer
Dim angle As Double
'opposite side , adjacent side
op = ptEnd.X - ptStart.X
adj = ptStart.Y - ptEnd.Y
'in radians
angle = Math.Atan(op / adj)
'in degrees
angle = angle / 2 / Math.PI * 360
'display it
TextBox1.Text = angle.ToString
End Sub
End Class