Problem calling a method from the paint event of a canvas

This has been an issue for a while but I’ve got around it by using graphics.DrawSomething. I know this has been deprecated in favour of g.DrawSomething, but the problem has now come to a point where I really need to understand and get it right.

In a canvas paint event I have g.Drawline (0,0,100,100) which draws a diagonal line from the top left corner of the canvas as expected.

If I move the code into a method, when compiling I get an error in the method: “This item doesn’t exist”. However, if I change it to graphics.Drawline (0,0,100,100), then I don’t get the error, BUT the diagonal line now draws from the top left corner of the application main window, not the original canvas.

According to the documentation
Canvas.Paint :

I don’t understand what that means, but I’m sure that’s where the problem is.

Help appreciated.

What is the code in the method ? Could you copy the entire method and post that, including the parameters ?

Thanks Michel. I’ve already posted the method as above. There is nothing else. Please re-read carefully my original post.

Steve, All I see is a couple of one liners using DrawLine, not methods. If you don’t pass g as parameter, it probably is the problem.

That is why I asked you to post the complete method, including parameters.

This works great here. Here is the method complete code :

Public Sub DrawThatLine(g as graphics) g.Drawline (0,0,100,100) End Sub

Content of Paint :

Sub Paint(g As Graphics, areas() As REALbasic.Rect) Handles Paint DrawThatLine(g) End Sub

Yes, that fixed it. Thanks Michel.


You may have come across the term “graphics context” used frequently. Every object that draws anything on screen has a graphics object attached to it. If you have a global method the draws a line, you have to tell it what object you want your drawing commands to affect.

Say you have two or more canvas objects. Each of course has a graphics context. Your global method will work as long as you pass the graphics context object to the method, just like Michel has shown above. This just tells the method which object you want to draw to. It really is as simple as that.

2018 XDC Attendee