Dino Prašo
Dino Prašo

Reputation: 611

Trying to remove a previously created border in Visual Basic

I have this code:

Sub drawborder()
    Dim objGraphics As Graphics
    objGraphics = Me.CreateGraphics
    objGraphics.Clear(System.Drawing.SystemColors.Control)
    objGraphics.DrawRectangle(System.Drawing.Pens.Red, picShowPicture.Left - 1,    picShowPicture.Top - 1, picShowPicture.Width + 1, picShowPicture.Height + 1)
    objGraphics.Dispose()
    borderstatus.Text = "Border Drawn"
End Sub

and this draws a border around a PictureBox. Now I want to use another button to remove it again but I can't seem to make it work.

Upvotes: 2

Views: 1230

Answers (2)

LarsTech
LarsTech

Reputation: 81620

Don't use CreateGraphics, that's just a temporary drawing that will be erased when you minimize the form or move it off screen, etc.

Try holding a variable and then just invalidate the form:

Private _ShowBorder As Boolean

Public Sub New()
  InitializeComponent()
  Me.DoubleBuffered = True
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  _ShowBorder = Not _ShowBorder
  Me.Invalidate()
End Sub

Protected Overrides Sub OnPaint(e As PaintEventArgs)
  e.Graphics.Clear(Me.BackColor)

  If _ShowBorder Then
    e.Graphics.DrawRectangle(Pens.Red, PictureBox1.Left - 1, PictureBox1.Top - 1, PictureBox1.Width + 1, PictureBox1.Height + 1)
  End If

  MyBase.OnPaint(e)
End Sub

Upvotes: 2

Anthony Benavente
Anthony Benavente

Reputation: 330

Make your graphics object global. Then you can call objGraphics.Clear(...) which should clear the screen of any drawn graphics. For example:

Dim objGraphics as Grahpics

Public Sub Form1_Load(...) Handles Form1.Load
    objGraphics = Me.CreateGraphics()
End Sub

Public Sub DrawBorder()
    objGraphics.Clear(System.Drawing.SystemColors.Control)
    objGraphics.DrawRectangle(System.Drawing.Pens.Red, picShowPicture.Left - 1,       picShowPicture.Top - 1, picShowPicture.Width + 1, picShowPicture.Height + 1)
    borderstatus.Text = "Border Drawn"
End Sub

Public Sub ClearScreen()
    objGraphics.Clear(System.Drawing.SystemColors.Control)
    borderstatus.Text = "No Border"
End Sub

Upvotes: 1

Related Questions