Page 1 of 1

Help-Using the cursor to draw a square

Posted: Fri Aug 03, 2012 5:19 am
by SumCode
Hey guys I am trying to draw a square by using the cursor and it draws on to the form. So far i have this code which i found on the internet, but it only works for the top-left part of the picture.
Code: Select all
Imports System.Drawing.Drawing2D
Public Class Form2
    Private _gr As Graphics
    Dim drag As Boolean = False
    Private _pt1, _pt2 As Point
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        _gr = Me.CreateGraphics
        Me.Size = My.Computer.Screen.Bounds.Size
        Me.Location = New Point(0, 0)
    End Sub

    Private Sub Form2_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
        _pt1 = New Point(e.X, e.Y)
        drag = True
    End Sub

    Private Sub DrawRect()
        If _pt1.X > _pt2.X And _pt1.Y > _pt2.Y Then
            _gr.FillRectangle(Brushes.Black, New Rectangle(_pt2.X, _pt2.Y, _pt1.X - _pt2.X, _pt1.Y - _pt2.Y))
        Else
            _gr.FillRectangle(Brushes.Black, New Rectangle(_pt1.X, _pt1.Y, _pt2.X - _pt1.X, _pt2.Y - _pt1.Y))
        End If
    End Sub

    Private Sub Form2_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        If drag = True Then
            _pt2 = New Point(e.X, e.Y)
            DrawRect()
        End If
    End Sub

    Private Sub Form2_MouseUp(sender As Object, e As MouseEventArgs) Handles Me.MouseUp
        _pt2 = New Point(e.X, e.Y)
        DrawRect()
        drag = False
    End Sub
End Class
Does anyone know hot to make it work for the entire picture.

Thanks and goodbye.

Re: Help-Using the cursor to draw a square

Posted: Fri Aug 03, 2012 10:04 am
by lolxot
replace the form2_load event with this:
Code: Select all
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Size = My.Computer.Screen.Bounds.Size
        _gr = Me.CreateGraphics
        Me.Location = New Point(0, 0)
End Sub

Re: Help-Using the cursor to draw a square

Posted: Fri Aug 03, 2012 2:34 pm
by MrAksel
That would not change anything. Replace the DrawRect code with this:
Code: Select all
Dim r As Rectangle = Rectangle.FromLTRB(Math.Min(_pt1.X, _pt2.X), Math.Min(_pt1.Y, _pt2.Y), Math.Max(_pt1.X, _pt2.X), Math.Max(_pt1.Y, _pt2.Y)
_gr.FillRectangle(Brushes.Black, r)

Re: Help-Using the cursor to draw a square

Posted: Fri Aug 03, 2012 3:28 pm
by SumCode
MrAksel wrote:
That would not change anything. Replace the DrawRect code with this:
Code: Select all
Dim r As Rectangle = Rectangle.FromLTRB(Math.Min(_pt1.X, _pt2.X), Math.Min(_pt1.Y, _pt2.Y), Math.Max(_pt1.X, _pt2.X), Math.Max(_pt1.Y, _pt2.Y)
_gr.FillRectangle(Brushes.Black, r)

Still only works for the top-left part of the picture. Would you like the source?