天天看点

Excel VBA UserForm窗体置顶

VBA窗口置顶功能

  1. 新建模块
  2. 插入下述代码
  3. 在UserForm中调用SetWinTopOrNot()
  4. 整理了一波,原创不易,收藏加评论,你的支持就是我的动力。
'  Forms
'->Module
'  ClassModules
'Function: VBA窗口置顶
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
Const SWP_NOSIZE = &H1
Const SWP_NOMOVE = &H2
Const SWP_NOACTIVATE = &H10
Const SWP_SHOWWINDOW = &H40
Private Declare Sub 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)
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
'[In] 1: TopWindows 0: Cancel TopWindows
'[Out] Msg of Result.
Public Function SetWinTopOrNot(ByVal Top As Boolean) As String
    'HWND FindWindowA(
    '  [in, optional] LPCSTR lpClassName,
    '  [in, optional] LPCSTR lpWindowName
    ');
    'Type: HWND
    'If the function succeeds, the return value is a handle to the window that has the specified class name and window name.
    Dim hwnd1
    hwnd1 = FindWindow("ThunderDFrame", vbNullString)
    'hwnd1 = FindWindow(vbNullString, Me.Caption)  'Recommand
    If Top = True Then
        SetWindowPos hwnd1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE
        SetWinTopOrNot "WindowIsPlacedTheTop Done!"
    Else
        SetWindowPos hwnd1, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE
        SetWinTopOrNot "WindowIsPlacedTheTop Cancel!"
    End If
End Function
           

VS2010 VB Form 置顶功能

  • Form初始化事件是 Active
    Excel VBA UserForm窗体置顶
'Declare Area
'  Forms
'->Module
'  ClassModules
'Function: VBA窗口置顶
Const HWND_TOPMOST = -1
Const HWND_NOTOPMOST = -2
Const SWP_NOSIZE = &H1
Const SWP_NOMOVE = &H2
Const SWP_NOACTIVATE = &H10
Const SWP_SHOWWINDOW = &H40
Private Declare Sub 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)
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
'[In] 1: TopWindows 0: Cancel TopWindows
'[Out] Msg of Result.
Public Sub SetWinTopOrNot(ByVal Top As Boolean)
    Dim hwnd As Long
    hwnd = FindWindow(vbNullString, Me.Text)
    If Top = True Then
        SetWindowPos(hwnd:=hwnd, hWndInsertAfter:=HWND_TOPMOST, x:=0, y:=0, cx:=0, cy:=0, wFlags:=SWP_NOSIZE Or SWP_NOMOVE)
    Else
        SetWindowPos(hwnd:=hwnd, hWndInsertAfter:=HWND_NOTOPMOST, x:=0, y:=0, cx:=0, cy:=0, wFlags:=SWP_NOSIZE Or SWP_NOMOVE)
    End If
End Sub
           
vba