You are on page 1of 2

' Written: July 07, 2009

' Author: Leith Ross


' Summary: Keeps a UserForm, or any window on top of all other windows.
' Call this macro from the UserForm_Activate event code module.

' This variable is initalized in the UserForm_Initialize() event. It holds the hWnd
to the Excel Application Window.
Global xlHwnd As LongPtr

' This API call is used to hide or show the Excel Application.
Public Declare PtrSafe Function ShowWindow _
Lib "user32.dll" _
(ByVal hwnd As LongPtr, _
ByVal nCmdShow As Long) _
As Long

' Returns the Window Handle of the Window that is accepting User input.
Private Declare PtrSafe Function GetForegroundWindow Lib "user32.dll" () As LongPtr

Private Declare PtrSafe Function SetWindowPos _


Lib "user32.dll" _
(ByVal hwnd As LongPtr, _
ByVal hWndInsertAfter As LongPtr, _
ByVal x As Long, _
ByVal Y As Long, _
ByVal cx As Long, _
ByVal cy As Long, _
ByVal wFlags As Long) _
As Long

Sub KeepFormOnTop()

Dim ret As Long

Const HWND_TOPMOST As Long = -1


Const SWP_NOMOVE As Long = &H2
Const SWP_NOSIZE As Long = &H1

ret = ShowWindow(xlHwnd, 0)
ret = SetWindowPos(GetForegroundWindow(), HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE + SWP_NOSIZE)

End Sub

Private Sub CommandButton1_Click()


Unload Me
End Sub

Private Sub UserForm_Activate()


Label1.Caption = "Next Show Time: " & Module1.dtmNextTime

Call Keep_Form_On_Top_64bit.KeepFormOnTop

End Sub
Private Sub UserForm_Initialize()
Keep_Form_On_Top.xlHwnd = Excel.Application.hwnd
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)


Dim ret As Long
ret = ShowWindow(xlHwnd, 1)
End Sub

You might also like