VBA窗体中最小化和最大化按钮的显示
不少朋友偏爱用VBA开发应用程序来解决日常办公中遇到的问题,可大家会发现在VBE编辑器中插入的窗体(默认为UserForm1)标题栏中只有“关闭”按钮而没有“最小化”和“最大化/还原”按钮(如图1)。网上也有朋友在解答这一问题时采用的是变通的方法,即在设计程序界面时通过设置窗体的属性隐去了窗体的标题栏,然后利用工具绘制出虚拟的标题栏,最后对“标题栏”中相应的“按钮对象”进行编程,这当然也是可以的,但无疑增加程序开发的难度同时也影响了程序界面的美观。其实利用API,我们可以方便地给这些窗体的标题栏加上最大化/还原和最小化按钮。
实现的方法是:在插入的用户窗体中双击鼠标,打开窗体的代码窗口,删除其中的默认事件(UserForm_Click()事件)代码,然后输入下面的API系统调用程序:
Option Explicit
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Const GWL_STYLE = (-16)
Private Const WS_THICKFRAME As Long = &H40000 '(恢复大小)
Private Const WS_MINIMIZEBOX As Long = &H20000 '(最小化)
Private Const WS_MAXIMIZEBOX As Long = &H10000 '(最大化)
'窗体UserForm的初始化
Private Sub UserForm_Initialize()
Dim hWndForm As Long
Dim IStyle As Long
hWndForm = FindWindow("ThunderDFrame", Me.Caption)
IStyle = GetWindowLong(hWndForm, GWL_STYLE)
IStyle = IStyle Or WS_THICKFRAME '还原
IStyle = IStyle Or WS_MINIMIZEBOX '最小化
IStyle = IStyle Or WS_MAXIMIZEBOX '最大化
SetWindowLong hWndForm, GWL_STYLE, IStyle
End Sub
完成后运行用户窗体就可以观察到如图2所示的效果了。