Skip to content

Instantly share code, notes, and snippets.

@craopt
Created January 21, 2017 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craopt/fb7f2a8338a2a75a84473e58499e10f1 to your computer and use it in GitHub Desktop.
Save craopt/fb7f2a8338a2a75a84473e58499e10f1 to your computer and use it in GitHub Desktop.
Switch the state of close button on WinForms.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace TestForm
{
public static class FormExtensions
{
[DllImport("USER32.DLL")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("USER32.DLL")]
private static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
private const uint SC_CLOSE = 0x0000F060;
private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_ENABLED = 0x00000000;
private const uint MF_GRAYED = 0x00000001;
private const uint MF_DISABLED = 0x00000002;
public static void EnableCloseButton(this Form form, bool enable)
{
IntPtr hMenu = GetSystemMenu(form.Handle, false);
uint command = enable ? MF_ENABLED : (MF_GRAYED | MF_DISABLED);
EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | command);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment