Graphics.StringWidth Error

The following code worked for years

w=Graphics.StringWidth("35")

Now with release 2019r1 I get the error

Static reference to instance method: call this on an instance of class graphics.

The error occurs in the paint event of a canvas.

Any ideas how to correct this?

Graphics is an object type… it is not an object instance (“g” might be an instance)

Where is that code?
It should be referencing the graphics property of a PICTURE object
like this

dim p as new picture(10,10)
dim g as graphics = p.graphics

or it should reference the passed “g” property in the PAINT EVENT of a canvas control
(note for a Canvas control that is the ONLY place the graphics property can be accessed directly)

Just a quick refresher… especially for those building for TargetWindows.
Be aware that you are using the appropriate TextRendering (Direct2D, GDI) when calculating .StringWidth.

.StringWidth will be different for:

  • dim p as new picture(1,1) (Direct2D, such as in alpha-supported Pictures and Printing)
  • dim p as new picture(1,1,32) (GDI, such as in GUI Controls .Paint Events and non alpha-supported Pictures)

If this is in the paint event you can just switch to:

w=g.StringWidth("35")

g is the instance of the Graphics object passed into the paint event.

[quote=438073:@Bob Keeney]If this is in the paint event you can just switch to:

w=g.StringWidth("35")

g is the instance of the Graphics object passed into the paint event.[/quote]
And that’s the best way, too! Because then you’re sure that you’re calculating in the “correct” kind of “Graphics Context”.
Why? Click on the Link above with all the details of TextRendering (on TargetWindows).

Thanks Bob. What an easy solution. This code is almost 10 years old, and I never experienced a problem before.