1

我有一个用户表单,在关闭时需要运行清理步骤。我希望X按钮被禁用和/或不可见,但我仍然需要能够卸载表单。我使用了像下面这样的代码,但它也阻止了Unload Me.

'Disables closing via x button
Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
    If CloseMode = vbFormControlMenu Then
        MsgBox ("BLOCKED")
        Cancel = True
    End If
End Sub
4

3 回答 3

6

UserForm_QueryClose在这种情况下不要使用。使用APIRemoveMenuGetSystemMenuFindWindow

是我最喜欢的 API 站点

删除菜单: http : //allapi.mentalis.org/apilist/RemoveMenu.shtml

获取系统菜单: http : //allapi.mentalis.org/apilist/GetSystemMenu.shtml

查找窗口: http : //allapi.mentalis.org/apilist/FindWindow.shtml

看这个例子

Option Explicit

Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, _
ByVal wFlags As Long) As Long

Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long

Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, _
ByVal lpWindowName As String) As Long

Private Const MF_BYPOSITION = &H400&

Private Sub UserForm_Initialize()
    Dim Ret As Long

    '~~> Change UserForm1 to match your userform's caption
    Ret = FindWindow("ThunderDFrame", "UserForm1")

    Do While Ret = 0
        '~~> Change UserForm1 to match your userform's caption
        Ret = FindWindow("ThunderDFrame", "UserForm1")
        DoEvents
    Loop

    RemoveMenu GetSystemMenu(Ret, 0), 6, MF_BYPOSITION
End Sub

Private Sub CommandButton1_Click()
    Unload Me
End Sub

截图

在此处输入图像描述

于 2013-04-04T10:51:40.193 回答
2

与其给用户一条消息说他不能点击红色的 x,不如按照你的方式捕获它,并在卸载表单之前进行清理:

Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
    If CloseMode = vbFormControlMenu Then
        ' run cleanup code here
    End If
End Sub

如果表单有一个关闭按钮来进行清理,那么使用这样的东西:

Sub UserForm_QueryClose(Cancel As Integer, ClsoeMode As Integer)
    If CloseMode = vbFormControlMenu Then
        ' click event code for Close button:
        btnClose_Click 
        Cancel = True
    End If
End Sub

无需过度使用 Windows API,因为这都是内置的。

于 2013-04-04T15:09:52.350 回答
1

我知道这是一个旧的提要,但你拼写ClsoeMode错误。只需将其更改为CloseMode,这应该可以解决您的问题。

于 2013-08-12T14:42:31.370 回答