Home Products Customers Tips VBA OfficeOne on Mac Contact us

Positioning VBA user forms using pixels

VBA user forms use points to position themselves. Most of the Win32 APIs deal with pixels. An inch has 72 points. The following code snippet converts from pixels to points. Another code snippet shows how to position user forms using this conversion function. We would position a user form on the right-most edge of the screen.

Private Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function ReleaseDC Lib "user32" ( _
    ByVal hWnd As Long, _
    ByVal hDC As Long) As Long
Private Declare Function GetDeviceCaps Lib "gdi32" ( _
    ByVal hDC As Long, _
    ByVal nIndex As Long) As Long

Const LOGPIXELSX = 88
Const LOGPIXELSY = 90
Const TWIPSPERINCH = 1440

Private Declare Function GetSystemMetrics Lib "user32" ( _
    ByVal nIndex As Long) As Long

Private Const SM_CXFULLSCREEN = 16
Private Const SM_CYFULLSCREEN = 17

Sub ConvertPixelsToPoints(ByRef X As Single, ByRef Y As Single)
    Dim hDC As Long
    Dim RetVal As Long
    Dim XPixelsPerInch As Long
    Dim YPixelsPerInch As Long

    hDC = GetDC(0)
    XPixelsPerInch = GetDeviceCaps(hDC, LOGPIXELSX)
    YPixelsPerInch = GetDeviceCaps(hDC, LOGPIXELSY)
    RetVal = ReleaseDC(0, hDC)
    X = X * TWIPSPERINCH / 20 / XPixelsPerInch
    Y = Y * TWIPSPERINCH / 20 / YPixelsPerInch
End Sub

Sub Test()
    Dim Wt As Single
    Dim Ht As Single

    Wt = GetSystemMetrics(SM_CXFULLSCREEN)
    Ht = GetSystemMetrics(SM_CYFULLSCREEN)
    With TestUserForm
        ConvertPixelsToPoints Wt, Ht
        .Left = Wt - .Width
        .Show vbModeless
    End With
End Sub


Home | Products | Tips | VBA | FAQ | Utilities | Disclaimer | Privacy Policy | Mac | Links | Contact us

Contact OfficeOne on email at officeone@officeoneonline.com. Copyright © 2001-2017 OfficeOne. All rights reserved.

page counter