有时候,我们可能需要禁用用户窗体上的关闭按钮[X]。例如,希望用户在关闭用户窗体之前必须要填写一些内容,或者设计带有进度条的用户窗体,或者隐藏关闭按钮可以使用户窗体看起来更友好。最简单的方式是使用UserForm_QueryClose事件禁止对关闭按钮进行操作。例如:Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = 0 Then
Cancel = True
MsgBox "已禁用关闭按钮[X].", vbCritical, "关闭按钮被禁用"
End If
End Sub
但这种方式就用户体验而言不是太好,因为在用户点击关闭按钮后得到不能使用的消息,所以最好是隐藏关闭按钮,这样用户就不需要考虑单击关闭按钮了。然而,在默认情况下,不能禁用用户窗体中的关闭按钮,但可以使用Windows
API来实现。在VBE中,插入一个标准模块,输入下面的代码:Private Const GWL_STYLE As Long = -16
Private Const WS_SYSMENU As Long = &H80000
Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr
Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long) As LongPtr
Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr
Private Declare PtrSafe Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As LongPtr, ByVal nIndex As Long) As LongPtr
Private Declare PtrSafe Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Sub RemoveCloseButton(frm As Object)
Dim lStyle As LongPtr, lFrmHandle As LongPtr
Dim lStyle As Long, lFrmHandle As Long
lFrmHandle = FindWindow("ThunderDFrame", frm.Caption)
lStyle = GetWindowLong(lFrmHandle, GWL_STYLE)
lStyle = lStyle And Not WS_SYSMENU
SetWindowLong lFrmHandle, GWL_STYLE, lStyle
End Sub
然后,在要移除关闭按钮的用户窗体代码模块中,输入下面的代码:Private Sub UserForm_Initialize()
RemoveCloseButton Me
End Sub
注意,在运行隐藏关闭按钮的代码之前,确保用户窗体上有一个可以用来关闭用户窗体的按钮。否则,你将只有回到VBE中停止代码运行才能关闭用户窗体。欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。
欢迎到知识星球:完美Excel社群,进行技术交流和提问,获取更多电子资料,并通过社群加入专门的微信讨论群,更方便交流。