This tip shows how to disable/enable the Close (X) Button in the titlebar of a window. The way that this is possible is by removing the "Close" item out of the System Menu for the window. For looks, the seperator before the "Close" item is also removed.
Add two command buttons (Command1 and Command2) to a form and add the following code...
Option Explicit
Private Const MF_BYPOSITION& = &H400&
Private Declare Function GetSystemMenu& Lib "user32" (ByVal hwnd As Long, ByVal bRevert As Long)
Private Declare Function RemoveMenu& Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long)
Private Declare Function GetMenuItemCount& Lib "user32" (ByVal hMenu As Long)
Private Sub Command1_Click()
Dim lHwnd As Long
Dim lSysMenu As Long
Dim lItemCount As Long
lHwnd = Me.hwnd
lSysMenu = GetSystemMenu(lHwnd, False)
lItemCount = GetMenuItemCount(lSysMenu)
RemoveMenu lSysMenu, lItemCount - 1, MF_BYPOSITION
RemoveMenu lSysMenu, lItemCount - 2, MF_BYPOSITION
End Sub
Private Sub Command2_Click()
Dim lHwnd As Long
Dim lSysMenu As Long
lHwnd = Me.hwnd
lSysMenu = GetSystemMenu(lHwnd, True)
End Sub
Command1 will disable the Close button and Command2 will enable it again.
Note: This code takes for granted that in the System Menu for the window that the "Close" item is the last item in the menu. You might need to adjust the "-1" or "-2" in the RemoveMenu functions to remove the correct menu items.
|