How to disable Close button of Windows Forms Application

We can disable the close button of a Windows Form in three ways

  1. Set controlbox property to false – It is most easy way to do this. But it also hides the Minimize and Maximize buttons.
  2. Using WIN32 API – Using Win32 API, we are getting the system menu and removes the close menu item using Remove menu item.
    Here is the Code.

    const int MF_BYPOSITION = 0x400;
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    
    //In the Form load event
    IntPtr hMenu = GetSystemMenu(this.Handle, false);
    int menuItemCount = GetMenuItemCount(hMenu);
    RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
    

    And here is the screenshot

    Using WIN32 API

    Using WIN32 API

  3. By Overriding the CreateParams property – The CreateParams property gets the required creation parameters when the control handle is created. By overriding the property we are removing the close button. You can get more information about CreateParams in MSDN
    Here is the code.

    private const int CS_CLOSE = 0x200;
    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams parms = base.CreateParams;
            parms.ClassStyle |= CS_CLOSE;  //
            return parms;
        }
    }
    

    And here is the screenshot

    By Overriding CreateParams property

    By Overriding CreateParams property

    All of above three methods will work fine. But if you are using Windows 7 none of the above will work or OS will override all these.

    Windows 7 - Close Window

    Windows 7 - Close Window

This entry was posted in .Net, .Net 3.0 / 3.5, Win 32 API, Windows 7, Windows Forms and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>