Jul 3, 2007

How to convert Twips to Pixels and back again

Description: Visual Basic uses Twips by default instead of pixels, this shows how to convert between them
Its very easy to convert between Twips and Pixels, using the Screen object.

Heres how to convert from Twips to Pixels for Horizontal (X axis) positions:

CODE: Pixels = Twips / Screen.TwipsPerPixelX


And for Vertical (Y axis) positions:

CODE: Pixels = Twips / Screen.TwipsPerPixelY



To convert back again, just use (for horizontal):

CODE: Twips = Pixels * Screen.TwipsPerPixelX

And for vertical:

CODE: Twips = Pixels * Screen.TwipsPerPixelY


On most systems you can use either horizontal or vertical but I presume in some cases you can't, so its best to use the correct ones.


MSFlexGrid uses twips, but .NET uses pixels. You can use the code below to
convert pixels to twips:


Private m_TwipsPerPixelX As Integer
Private m_TwipsPerPixelY As Integer
....
Using g As Graphics = Me.CreateGraphics()
m_TwipsPerPixelX = 1440 / g.DpiX
m_TwipsPerPixelY = 1440 / g.DpiY
End Using
....
Me.MSFlexGrid1.ColWidth = 100 * m_TwipsPerPixelX