2013-04-04 42 views
1

我有一個用戶窗體,關閉時需要運行清理步驟。我希望X按鈕被禁用和/或不可見,但我仍然需要能夠卸載表單。我使用下面的代碼,但它也會阻止Unload Me禁用VBA UserForm'x',但仍然允許卸載我

'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 

回答

6

不要在這種情況下使用UserForm_QueryClose。使用API​​ RemoveMenuGetSystemMenuFindWindow

This是我最喜歡的網站的API

RemoveMenuhttp://allapi.mentalis.org/apilist/RemoveMenu.shtml

GetSystemMenuhttp://allapi.mentalis.org/apilist/GetSystemMenu.shtml

FindWindow函數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 

截圖

enter image description here

+0

這是使用什麼庫,它可以作爲參考添加,而不是使用頂部的聲明引用? – steventnorris 2013-04-04 11:57:42

+0

聲明函數中提到了庫的名稱。不需要,你必須在頂部宣佈這一點。 – 2013-04-04 12:21:17

+0

謝謝。我研究了這種方法,發現了一些可能對我的案例更好的工作。而不是禁用,我將使用布爾值來確定X按鈕是否被接受或不在UserForm_QueryClose中。我接受你的答案,但是,因爲它回答了OP。再次感謝! – steventnorris 2013-04-04 12:33:04

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的太過火,因爲這是所有內置。

1

我知道這是一箇舊飼料,但你拼寫ClsoeMode錯誤。只需將其更改爲CloseMode,這可以解決您的問題。

相關問題