Freehand drawing using VB.NET

On a Windows Form, add a PictureBox control named PictureBox1 and write the code below on the MouseDown, MouseUp, and MouseMove events of the PictureBox.

Press left mouse button and move the mouse in the form as you see a line will be drawn until mouse is up, wherever you move the mouse.

Imports System.Drawing

Imports System.Drawing.Drawing2D

Public Class Form1

    Public eventString As String

    Public pw As Integer

    'Public j As Integer

    'Public p As Integer

    'Public q As Integer

    Private Sub PictureBox1_MouseDown(ByVal sender As ObjectByVal e AsSystem.Windows.Forms.MouseEventArgs) 
Handles PictureBox1.MouseDown

        ' i = e.X

        ' j = e.Y

        ' p = e.X

        'q = e.Y

        pw = 4 ' you can use numeric updown for selecting pen-width

        Select Case e.Button

            Case MouseButtons.Left

                eventString = "L"

            Case MouseButtons.Right

                eventString = "R"

            Case MouseButtons.Middle

                eventString = "M"

            Case MouseButtons.XButton1

                eventString = "X1"

            Case MouseButtons.XButton2

                eventString = "X2"

            Case MouseButtons.None

                eventString = Nothing

        End Select

    End Sub

    Private Sub PictureBox1_MouseMove(ByVal sender As ObjectByVal e AsSystem.Windows.Forms.MouseEventArgs)
 Handles PictureBox1.MouseMove

        Dim yourArray As Point() = {New Point(e.X - pw, e.Y - pw), New Point(e.X, e.Y)}

        Dim cle As Graphics

        Dim myPath As New GraphicsPath

        Dim mykolor As Color

        cle = PictureBox1.CreateGraphics

        If eventString = "L" Then

            mykolor = Color.Blue 'here you can select color using colordialogbox

            myPath.StartFigure()

            myPath.AddLines(yourArray)

            myPath.CloseFigure()

            cle.DrawPath(New Pen(mykolor, pw), myPath)

        End If

        If eventString = Nothing Then

            myPath.Reset()

            cle.Flush()

        End If

    End Sub

    Private Sub PictureBox1_MouseUp(ByVal sender As ObjectByVal e AsSystem.Windows.Forms.MouseEventArgs)
 Handles PictureBox1.MouseUp

        eventString = Nothing

    End Sub

End Class

Up Next
    Ebook Download
    View all
    Learn
    View all