Friday, December 19, 2008

How to disable close button from window form using .NET application

How to disable window close button ("X") in .NET


VB.NET

                       

To disable close button from the window form using vb.net needs some Dlls from system library. Call DisableCloseButton(me.Handle) function from your window form button click event or from where you want to disable "x" button.

Code-1

 

Private Const MF_BYPOSITION As Int32 = &H400

Private Const MF_REMOVE As Int32 = &H1000


Private Declare Auto Function GetSystemMenu Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal bRevert As Int32) As IntPtr


Private Declare Auto Function GetMenuItemCount Lib "user32.dll" (ByVal hMenu As IntPtr) As Int32


Private Declare Function DrawMenuBar Lib "user32.dll" (ByVal hwnd As IntPtr) As Boolean


Private Declare Auto Function RemoveMenu Lib "user32.dll" (ByVal hMenu As IntPtr, ByVal nPosition As Int32, ByVal wFlags As Int32) As Int32


'This method will be used to disable the Form "X" button

Public Shared Sub DisableCloseButton(ByVal hwnd As IntPtr)

Dim hMenu As IntPtr, n As Int32

hMenu = GetSystemMenu(hwnd, 0)

If Not hMenu.Equals(IntPtr.Zero) Then

              n = GetMenuItemCount(hMenu)

     If n > 0 Then

                   RemoveMenu(hMenu, n - 1, MF_BYPOSITION Or MF_REMOVE)

         RemoveMenu(hMenu, n - 2, MF_BYPOSITION Or MF_REMOVE)

                   DrawMenuBar(hwnd)

     End If

End If

End Sub

Code-2

Another way to disable close button from window form , override  "CreateParams" property. You have to Include following code in your in your window form.

     Private Const CP_NOCLOSE_BUTTON As Integer = &H200

     Protected Overloads Overrides ReadOnly Property CreateParams() As    CreateParams

         Get

             Dim myCp As CreateParams = MyBase.CreateParams

    myCp.ClassStyle = myCp.ClassStyle Or CP_NOCLOSE_BUTTON

              Return myCp

End Get

     End Property

C#.NET

In C#.net its simple just override "CreateParams" property, that's all.

Including following code in your in your window form.

private const int CP_NOCLOSE_BUTTON = 0x200;

protected override CreateParams CreateParams

{

   get

   {

      CreateParams myCp = base.CreateParams;

      myCp.ClassStyle = myCp.ClassStyle | CP_NOCLOSE_BUTTON;

      return myCp;

    }

 }

1 comment:

Anonymous said...

Either VB solution works great. Thanks.