Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleDisable the close X in a form's upper right corner
Keywordsform, close, unload
CategoriesControls, API
 
Use API functions to remove the Close item from the system menu.
 
Private Sub Form_Load()
    ' Remove the Close system menu item and the
    ' menu separator.
    RemoveMenus Me, False, False, _
        False, False, False, True, True
End Sub

Private Sub RemoveMenus(ByVal frm As Form, _
    ByVal remove_restore As Boolean, _
    ByVal remove_move As Boolean, _
    ByVal remove_size As Boolean, _
    ByVal remove_minimize As Boolean, _
    ByVal remove_maximize As Boolean, _
    ByVal remove_seperator As Boolean, _
    ByVal remove_close As Boolean)
Dim hMenu As Long
    
    ' Get the form's system menu handle.
    hMenu = GetSystemMenu(frm.hwnd, False)
    
    If remove_close Then DeleteMenu hMenu, 6, MF_BYPOSITION
    If remove_seperator Then DeleteMenu hMenu, 5, _
        MF_BYPOSITION
    If remove_maximize Then DeleteMenu hMenu, 4, _
        MF_BYPOSITION
    If remove_minimize Then DeleteMenu hMenu, 3, _
        MF_BYPOSITION
    If remove_size Then DeleteMenu hMenu, 2, MF_BYPOSITION
    If remove_move Then DeleteMenu hMenu, 1, MF_BYPOSITION
    If remove_restore Then DeleteMenu hMenu, 0, _
        MF_BYPOSITION
End Sub
 
Unfortunately removing the Close menu item does not prevent Alt-F4 from closing the form. Use a Boolean variable to decide when you should unload. Cancel all other unloads in the form's QueryUnload event handler.
 
Private ReadyToClose As Boolean

Private Sub cmdClose_Click()
    ReadyToClose = True
    Unload Me
End Sub

' Cancel if ReadyToClose is false.
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode _
    As Integer)
    Cancel = Not ReadyToClose
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated