How to Disable a Windows Close Button

 When you try out this sample, you may want to have an alternate way to close your window.
In this example, I will show you how you can disable the 'X' button found on every window. To achieve this, we will make use of several API calls in order to remove the Close item from the windows system menu. By so doing, we will have disabled the close button. In case you do this, then you have to put a code under a button etc so that the user can have an alternative way of closing the form.
Sometimes as a developer, you may find this necessary depending on what you are doing or in order to achieve a certain end. In my case, I do prefer to disable the close button by setting the Forms ControBox property to false.  See example below.





Steps
1. Create a module
2. Insert the code below into the module you created in step 1 above.


Option Explicit

Public Declare Function GetSystemMenu Lib "user32" _
    (ByVal hwnd As Long, _
     ByVal bRevert As Long) As Long

Public Declare Function RemoveMenu Lib "user32" _
    (ByVal hMenu As Long, _
     ByVal nPosition As Long, _
     ByVal wFlags As Long) As Long

Public Const MF_BYPOSITION = &H400&


Public Sub DisableCloseWindowButton(frm As Form)

    Dim hSysMenu As Long

    'Get the handle to this windows
    'system menu
    hSysMenu = GetSystemMenu(frm.hwnd, 0)

    'Remove the Close menu item
    'This will also disable the close button
    RemoveMenu hSysMenu, 6, MF_BYPOSITION

    'Lastly, we remove the seperator bar
    RemoveMenu hSysMenu, 5, MF_BYPOSITION

End Sub
'--end code block
Now call the DisableCloseWindowButton from your forms load event.

3. Put the following code uner Form_Load
   DisableCloseWindowButton Me
Do as shown below.

Private Sub Form_Load()
    DisableCloseWindowButton Me
End Sub
'--end code block

Comments

Popular posts from this blog

CREATING CRYSTAL REPORTS VB.NET 2012 STEP BY STEP - PART 2

How to paste image into picturebox from clipboard with VB.Net

How to Create Crystal Report using Visual Studio 2012 Part 1