DisableClose


Description:
This routine allows you to disable and re-enable the 'X' in the top corner of any form. Usage should be self-explanatory.
 
Code:
Option Explicit

Private Declare Function GetSystemMenu Lib "user32" (ByVal hwnd As _
   Long, ByVal bRevert As Boolean) 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 Declare Function DrawMenuBar Lib "user32" _
   (ByVal hwnd As Long) As Long

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

Public Sub DisableClose(frm As Form, Optional Disable As Boolean = True)
    'Setting Disable to False disables the 'X', otherwise, it's reset

    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
 
Sample Usage:
 
     DisableClose Me