Goood
Goood

Reputation: 21

Where to declare a public object which refer to a VB object?

First time that I use Visual Studio and VB.net.

Could someone explain to me where to declare a public object which refers to a VB object ?

This code works fine :

Public Class Form1

    Private ThePen As New System.Drawing.Pen(Color.Red)

    Private Sub Line(A As Point, y As Point)
       Dim NewGraphic As Graphics = PictureBox1.CreateGraphics()
       NewGraphic.DrawLine(ThePen, A, B)
       NewGraphic.Dispose()
    End Sub

End Class

But I would like to declare only one time in public

Dim NewGraphic As Graphics = PictureBox1.CreateGraphics()

I tried to declare it at the beginning, but it seem that my object PictureBox1 is not yet loaded (so, can't access PictureBox1.CreateGraphics())

So I tried in

Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

But I can't declare public variable inside :(

Upvotes: 1

Views: 165

Answers (2)

Goood
Goood

Reputation: 21

So different view but interesting !

I'm unable to test it :( There's a problem with e. object in

e.Graphics.DrawLine(Pens.Red, lineStart, lineEnd)

BC30456 Visual Basic 'Graphics' is not a member of 'EventArgs'.

Upvotes: 0

jmcilhinney
jmcilhinney

Reputation: 54457

You should pretty much NEVER call CreateGraphics. Draw on a control in its Paint event handler or, if appropriate, create a custom control and override the OnPaint method. Store the data that represents the drawing in one or more fields and, whenever you want to change the drawing, set those fields and call Invalidate on the control.

Private lineStart As Point
Private lineEnd As Point

Private Sub DrawLine(start As Point, [end] as Point)
    lineStart = start
    lineEnd = [end]
    PictureBox1.Invalidate()
End Sub

Private Sub PictureBox1_Paint(sender As Object, e As EventArgs) Handles PictureBox1.Paint
    e.Graphics.DrawLine(Pens.Red, lineStart, lineEnd)
End Sub

Generally speaking, it is preferable to specify the area to invalidate rather than not specifying an argument and invalidating the entire control. It is actually painting the pixels to the screen that is the slow part so it is preferable to keep that to a minimum. I'll leave that part to you but you may like to check this out for more info. Note that, if you're moving a line, you'd need to invalidate the area that contained the old line and the area that will contain the new line. You can call Invalidate multiple times with different areas in such cases, or you can combine the areas into one Region and call it once.

Upvotes: 1

Related Questions