Ken Kopczyk

Hurdles in .NET Development

Archive for the ‘WinForms Tips’ Category

Disabling and Enabling the Close Button in .NET 2.0 WinForms

Posted by Ken on January 23, 2010

In .NET 2.0 WinForms, the user is given the following control over the minimize/maximize/close buttons (otherwise known as the ControlBox):

  • Disable/enable the Minimize button via the Form.MinimizeBox property
  • Disable/enable the Maximize button via the Form.MaximizeBox property
  • Show/hide the entire ControlBox via the Form.ControlBox property

However, you may want to allow maximizing and minimizing, but remove the user’s ability to close the application using the close button for any number of reasons. For example:

  • You want to run some process that cannot be cancelled midway through.
  • You want to ensure a user completes some number of tasks before being able to exit.

Unfortunately, this functionality is not supported by default. One must leverage the unmanaged code of the Windows API to achieve this behavior:

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

public class SuperForm : Form
{ 
    private const int MF_BYPOSITION = 0x400;

    protected void DisableCloseButton()
    {
        IntPtr hMenu = GetSystemMenu(this.Handle, false);
        int menuItemCount = GetMenuItemCount(hMenu);
        RemoveMenu(hMenu, menuItemCount - 1, MF_BYPOSITION);
        DrawMenuBar((int)this.Handle);
    }
    protected void EnableCloseButton()
    {
        GetSystemMenu(this.Handle, true);
        DrawMenuBar((int)this.Handle);
    }

    // Win32 API declarations
    [DllImport("User32")]
    private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
    [DllImport("User32")]
    private static extern int GetMenuItemCount(IntPtr hWnd);
    [DllImport("User32")]
    private static extern int RemoveMenu(IntPtr hMenu, int nPosition, int wFlags);
    [DllImport("User32")]
    private static extern IntPtr DrawMenuBar(int hwnd);
}

Notice that I incorporated this functionality into a base class that all your forms can inherit from to gain this ability.

Advertisements

Posted in WinForms Tips | Tagged: , | 5 Comments »