|
In some situation during your project you did not need or want the close button of your form. This article is about how you can disable the close button of your form using the window API’s.
Steps you will do
Start visual studio and create a new window application.
Drop two button controls on the form.
Set the properties of the First as below:
Name = btnDisable, Text = Disable Close Button
Set the properties of the Second as below:
Name = btnClose, Text = Close Me
Drop a label control on your form and set its Text property as below:
Text = It is very simple to disable the close button of form.
Declare the following functions:
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Long) As IntPtr
Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As IntPtr, ByVal bRevert As Boolean) As IntPtr
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As IntPtr) As Integer
Private Declare Function DrawMenuBar Lib "user32" (ByVal hwnd As IntPtr) As Boolean
Private Const MF_BYPOSITION = &H400
Private Const MF_REMOVE = &H1000
Private Const MF_DISABLED = &H2
Now write the following function which will disable the close button of your form.
Public Sub DisableCloseButton(ByVal hwnd As IntPtr)
Dim hMenu As IntPtr
Dim menuItemCount As Integer
hMenu = GetSystemMenu(hwnd, False)
menuItemCount = GetMenuItemCount(hMenu)
Call RemoveMenu(hMenu, menuItemCount - 1, _
MF_DISABLED Or MF_BYPOSITION)
Call RemoveMenu(hMenu, menuItemCount - 2, _
MF_DISABLED Or MF_BYPOSITION)
Call DrawMenuBar(hwnd)
End Sub
In the click event of “btnClose” write the code to exit from application as below:
'To exit from the application
Application.Exit()
· In the click event of “btnDisable” write call the “DisableCloseButton” function to disable the close button as below:
'To call the function by passing the handler of form
DisableCloseButton(Me.Handle)
|