Source code for Issue Number 2

Copyright 1997-2000 by C&D Programming Corp. All Rights Reserved. Source code may not be reproduced except for use in a compiled executable. All rights reserved. If you would like to reprint any or all of this code please email us at info@codeoftheweek.com

Code of the Week Home


Source Code

To use this source code, just paste it into a module in your project and call the AlwaysOnTop subroutine from within your application.

'----------------------------------------------------------------------
'
'   Module Name:    basForms
'   Written By:     C&D Programming Corp.
'   Create Date:    1/7/98
'   Copyright:      Copyright 1997-98 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'
'   Purpose:        Determine the decimal equivalent of a fraction
'                   or whole number.
'
'
'----------------------------------------------------------------------
' The SetWindowPos API call is the trick to getting the
' always on top feature to turn on and off.
#If Win16 Then
    Declare Sub SetWindowPos Lib "User" (ByVal hWnd As Integer, ByVal hWndInsertAfter As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal wFlags As Integer)
#Else
    Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
#End If

' Set some constant values for SetWindowPos (from WINAPI.TXT).
Public Const SWP_NOACTIVATE = &H10
Public Const SWP_SHOWWINDOW = &H40
Public Const HWND_NOTOPMOST = -2
Public Const HWND_TOPMOST = -1

Public Sub AlwaysOnTop(frm As Form, bOnTop As Boolean)
    ' Turn on the TopMost attribute.
    '
    ' Also passes the current position and size
    ' in Pixels.  Since window coordinates in
    ' VB are usually Twips we do a division to
    ' determine the correct number of pixels.
    If bOnTop Then
        lFlag = HWND_TOPMOST
    Else
        lFlag = HWND_NOTOPMOST
    End If
    SetWindowPos frm.hWnd, lFlag, _
        frm.Left / Screen.TwipsPerPixelX, _
        frm.Top / Screen.TwipsPerPixelY, _
        frm.Width / Screen.TwipsPerPixelX, _
        frm.Height / Screen.TwipsPerPixelY, _
        SWP_NOACTIVATE Or SWP_SHOWWINDOW
End Sub