Monday, June 29, 2009

Disable close button on form

Insert this code to your module:

Option Explicit

Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function GetDesktopWindow Lib "user32" () As Long
Private Declare Function GetMenu Lib "user32" (ByVal hwnd As Long) As Long


Private Declare Function GetMenuInfo Lib "user32" (ByVal hwnd As Long, mInfo As MENUINFO) As Long
Private Declare Function GetSubMenu Lib "user32" (ByVal hMenu As Long, ByVal nPos As Long) As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long) As Long
Private Declare Function GetWindowDC Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function SetMenuInfo Lib "user32" (ByVal hwnd As Long, mInfo As MENUINFO) As Long
Private Declare Function GetMenuItemCount Lib "user32" (ByVal _
hMenu As Long) As Long
Private Declare Function RemoveMenu Lib "user32" (ByVal _
hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) _
As Long

Private Const MF_BYPOSITION = &H400&
Private Const MF_REMOVE = &H1000&

Private Type MENUINFO
cbSize As Long
fMask As Long
dwStyle As Long
cyMax As Long
hbrBack As Long
dwContextHelpID As Long
dwMenuData As Long
End Type

Private Sub DisableClose(frm As Form, Optional _
Disable As Boolean = True)

Dim hMenu As Long
Dim nCount As Long

If Disable Then
hMenu = GetSystemMenu(frm.hwnd, False)
nCount = GetMenuItemCount(hMenu)

Call RemoveMenu(hMenu, nCount - 1, MF_REMOVE Or _
MF_BYPOSITION)
Call RemoveMenu(hMenu, nCount - 2, MF_REMOVE Or _
MF_BYPOSITION)

DrawMenuBar frm.hwnd
Else
GetSystemMenu frm.hwnd, True

DrawMenuBar frm.hwnd
End If

End Sub


1 comment:

  1. You can disable a form's closing when the Close Button was clicked by using the form's standard QueryUnload event

    Private Sub Form_QueryUnload(Cancel as Integer, UnloadMode as Integer)
    If UnloadMode = vbFormControlMenu then
    Cancel=True
    End If
    End Sub

    (The 'Post a Comment' dialog disallows spaces or tabs to begin a line, and it disallows pasting, else the code above would be indented properly...)

    ReplyDelete