This article shows you how to create a small Visual Basic .Net project using Mouse Pointer to draw line in a PictureBox control. Mouse Pointer events (MouseDown, MouseMove, and MouseUp) are used in this article. However, if you draw a new line pass through some parts of the existing line in the box then it will erase those parts.Note: picRegion in code below is a name of PictureBox control
- Global Variable
Private startX As Integer = 0 'start position x of line Private startY As Integer = 0 'start position y of line Private oldEndX As Integer = 0 'the previous ending position x Private oldEndY As Integer = 0 'the previous ending position y Private gBitmap As Bitmap 'bitmap to place in picturebox Private isMouseDown As Boolean = False 'recognize mouse down or up
- Mouse Down Event: is to get position X and Y for the beginning point of line.
Private Sub picRegion_MouseDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles picRegion.MouseDown isMouseDown = True startX = e.X startY = e.Y End Sub
- Mouse Move Event: process only while mouse pointer being pressed.
1. Delete previous line by draw another line with background color
2. Draw another line with black color with the current ending point
Private Sub picRegion_MouseMove(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles picRegion.MouseMove If isMouseDown = True Then 'draw line during move Dim g As Graphics = Graphics.FromImage(gBitmap) g.DrawLine(New Pen(Me.picRegion.BackColor), startX, startY, oldEndX, oldEndY) picRegion.Image = gBitmap g.DrawLine(Pens.Black, startX, startY, e.X, e.Y) picRegion.Image = gBitmap ' oldEndX = e.X oldEndY = e.Y End If End Sub
- Mouse Up Event: just note that mouse pointer does not pressed anymore.
Private Sub picRegion_MouseUp(ByVal sender As Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles picRegion.MouseUp isMouseDown = False End Sub
- Form Load: create new bitmap object to be a region for drawing
Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load gBitmap = New Bitmap(picRegion.Width, picRegion.Height) End Sub
Download Source Code Here