I'm trying to get familiar with graphics in vb.net and want to draw just a straight line going from the top left to the bottom right of my form Form1
without using the Form1_Paint
method but by using Button1
However, the line is only drawn about a quarter of the way and stops as shown in the picture:
I think I need to increase the Clip of the Graphics Object z
and I tried the following but it doesn't work. I also tried decreasing the Clip size and that worked as expected.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
z.Clip.MakeInfinite()
z.DrawLine(pen1, 0, 0, Me.Size.Width, Me.Size.Height)
End Sub
pen1
and z
are initialized at the start of the program as follows:
Dim z As Graphics = CreateGraphics()
Dim pen1 = New Pen(Color.Black, 3)
I also tried using different set values for the x2 and y2 but nothing managed to be drawn outside of the box apart from using Form1_paint
.
CodePudding user response:
It has nothing to do with the clip, and everything to do with WHEN you called CreateGraphics()
. At the point that the graphics was created, the form was not fully initialized and it is using the incorrect size.
When you use CreateGraphics() or create a Pen, you should explicitly Dispose() of them as soon as you're done. This is best accomplished via a Using block:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using z As Graphics = CreateGraphics()
Using pen1 = New Pen(Color.Black, 3)
z.DrawLine(pen1, 0, 0, Me.ClientSize.Width, Me.ClientSize.Height)
End Using
End Using
End Sub
In general, though, using CreateGraphics() in this manner is almost always the INCORRECT approach. The line drawn this way is TEMPORARY. Minimize the form and restore it and the line will be gone.